import ctypes
import sys
import os
import string
import win32file
from datetime import date
from wx._misc import DropTarget, DataObject
from wxPython._controls import wxTextCtrl
import ConfigParser
from win32con import WM_DROPFILES, WM_COPYDATA
from win32com.client import Dispatch
from shutil import copyfile
from sqlalchemy.sql.functions import localtime
from adodbapi.adodbapi import Date, STRING
from winappdbg.win32.kernel32 import GetCurrentProcessId
from paramiko.sftp_attr import SFTPAttributes
from wx._controls import LIST_FORMAT_RIGHT, LIST_FORMAT_LEFT, LIST_FORMAT_CENTER
from Tkinter import EXCEPTION
sys.path = [os.getcwd()] + sys.path
import shutil
import webbrowser
import pythoncom
import wx.lib.mixins.listctrl as listmix 
#import glob
import paramiko
import time
import threading
import urllib
import win32api
import win32con
from ctypes.wintypes import MAX_PATH
from win32com.client import GetObject
import subprocess
import socket
import zipfile
import ftplib
import MySQLdb
#import encodings
#import tkFont
#import repr
import re
#from time import sleep, localtime, strftime
import wx.lib.agw.buttonpanel as bp
from wx.lib.stattext import GenStaticText as StaticText
#import wx.lib.agw.aquabutton as AB
import wx.lib.agw.gradientbutton as GB
import wx
#wx.SetDefaultPyEncoding('c')
#reload(sys)
#sys.setdefaultencoding('utf-8')
######print wx.GetDefaultPyEncoding()
#reload(sys)

######print wx.GetDefaultPyEncoding()
######print wx.Locale_GetSystemEncodingName()
#####print sys.getdefaultencoding()
######print sys.getfilesystemencoding()

sys.setdefaultencoding(wx.GetDefaultPyEncoding())
#####print wx.GetDefaultPyEncoding()
from ctypes import *
#from wx._controls import TextCtrl
#from wxPython._controls import wxTextCtrl
try:
    py_encoding = wx.GetDefaultPyEncoding()
except:
    pass
    #####print "unavailable"
#import StringIO, binascii
#from pickle import TRUE
#from cvCreateTrackbar import range
#from Pyrex.Plex.Regexps import Range

flagClick = False

class COLORREF(Structure):
    _fields_ = [
    ("byRed", c_byte),
    ("byGreen", c_byte),
    ("byBlue", c_byte)
    ]

# Menu structure used in calls to SetMenuInfo
class MENUINFO(Structure):
    _fields_ = [
    ("cbSize", c_long),
    ("fMask", c_long),
    ("dwStyle", c_long),
    ('cyMax', c_long),
    ("hbrBack", c_long),
    ("dwContextHelpID", c_long),
    ("dwMenuData", c_long)
    ]

PROCNAME = "SSHClient_WX.exe"
HOST = 'elisoft.co.kr'
USER = 'elisoft'
PASS = '7890'
DIRN = '/setup_eli_ssh'
FILE = 'SSHClient_WX.zip'
VERSION_FILE = 'version.txt'
VERSION_FILE_TEMP = 'version_temp.txt'
######print VERSION_FILE
######print VERSION_FILE_TEMP
DIRN_DES = ''
FILE_DES = 'SSHClient.zip'
APP_NAME = 'SSHClient_WX'
UPDATE_FILE = "update.exe"
DOWNLOAD_COUNT = 0.0
fileSize = 0

global f, fileSave

class UpdateDlg(threading.Thread, wx.Frame):
    def __init__(self, master):
        self.master = master
        threading.Thread.__init__(self)
        wx.Frame.__init__(self, self.master, -1, 'Update Programe Dialog', size=(335, 200), style=wx.FRAME_FLOAT_ON_PARENT | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU)
        
        #Create toolbar
        self.panel = wx.Panel(self, -1)
        self.box = wx.BoxSizer(wx.VERTICAL)
        self.panel.SetSizer(self.box)
        self.panel.SetAutoLayout(True)
        
        self.static = wx.StaticText(self.panel, -1, "Downloading for updating", (100, 20), (300, -1))
        self.gauge = wx.Gauge(self.panel, -1, 100, (10, 50), (300, 25))
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        
        self.btcancel = GB.GradientButton(self.panel, -1, None, "Cancel", size=(80, 30) , pos=(120, 100))
        self.btcancel.SetTopStartColour(wx.Colour(0, 128, 192))
        self.btcancel.SetTopEndColour(wx.Colour(0, 102, 151))
        self.btcancel.SetBottomStartColour(wx.Colour(0, 102, 151))
        self.btcancel.SetBottomEndColour(wx.Colour(0, 72, 106))
        self.btcancel.SetPressedTopColour(wx.Colour(0, 128, 192))
        self.btcancel.SetPressedBottomColour(wx.Colour(0, 124, 185))
        self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btcancel)
        
      
    
    def OnCancel(self, event):
        pass
        
    def OnExit(self, event):
        self.Destroy()
        #self.result = event.EventObject.GetId()
        #if self.callback <> None:
        #       self.callback()
    
class UpdateApplication(threading.Thread):
    def __init__(self, master):
        threading.Thread.__init__(self)
        self.master = master
        #self.updatedlg = UpdateDlg(self.master)
        self.CreateUpdateDlg()
        self.flag = True
        #self.updatedlg.Show()
       
        
        
  
    def CreateUpdateDlg(self):
        #dlg = wx.MessageDialog(self.master,"Do you want to update the new version ?", 'Notification', wx.YES_NO | wx.ICON_QUESTION)
        #if dlg.ShowModal() == wx.ID_YES:
        self.updatedlg = wx.Frame(self.master, -1, 'Update Programe Dialog', size=(335, 200), style=wx.FRAME_FLOAT_ON_PARENT | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU)
        self.updatedlg.CenterOnParent()
        #Create toolbar
        self.updatedlg.panel = wx.Panel(self.updatedlg, -1)
        self.updatedlg.box = wx.BoxSizer(wx.VERTICAL)
        self.updatedlg.panel.SetSizer(self.updatedlg.box)
        self.updatedlg.panel.SetAutoLayout(True)
        
        self.updatedlgstatic = wx.StaticText(self.updatedlg.panel, -1, "Downloading for updating", (100, 20), (300, -1))
        self.updatedlggauge = wx.Gauge(self.updatedlg.panel, -1, 100, (10, 50), (300, 25))
        
        
        self.updatedlg.btcancel = GB.GradientButton(self.updatedlg.panel, -1, None, "Cancel", size=(80, 30) , pos=(120, 100))
        self.updatedlg.btcancel.SetTopStartColour(wx.Colour(0, 128, 192))
        self.updatedlg.btcancel.SetTopEndColour(wx.Colour(0, 102, 151))
        self.updatedlg.btcancel.SetBottomStartColour(wx.Colour(0, 102, 151))
        self.updatedlg.btcancel.SetBottomEndColour(wx.Colour(0, 72, 106))
        self.updatedlg.btcancel.SetPressedTopColour(wx.Colour(0, 128, 192))
        self.updatedlg.btcancel.SetPressedBottomColour(wx.Colour(0, 124, 185))
       
        self.updatedlg.Show()
        self.updatedlg.Bind(wx.EVT_CLOSE, self.OnExit)
        self.updatedlg.Bind(wx.EVT_BUTTON, self.OnCancel, self.updatedlg.btcancel)
         
    def OnCancel(self, event):
        try:
            self.master.Enable(True)
            
            global fileSave, f
            self.flag = False            
            
            f.close()
            
            fileSave.close()
            self.updatedlg.Destroy()
        except Exception, e:
            ######print type(e)
            ######print e
            self.updatedlg.Destroy()
            return
       
        
        
    def OnExit(self, event):
        self.master.Enable(True)
        self.updatedlg.Destroy()
        global fileSave, f
        f.quit()
        try:
            fileSave.close()
        except:
            pass
        

             
    def downloadUpdateFile(self):
        
        rs = False            
        try:
            global f
            f = ftplib.FTP(HOST)
        except (socket.error, socket.gaierror):
            pass
            ######print 'ERROR: cannot reach "%s"' % HOST
                
        ######print '*** Connected to host "%s"' % HOST

        try:
            f.login(USER, PASS)
        except ftplib.error_perm:
            ######print 'ERROR: cannot login anonymously'
            #self.master.enableMenu()
            f.quit()
            #return
        ######print '*** Logged in as "anonymous"'

        try:
            f.cwd(DIRN)
        except ftplib.error_perm:
            ######print 'ERROR: cannot CD to "%s"' % DIRN
            #self.master.enableMenu()
            f.quit()
            #return
        ######print '*** Changed to "%s" folder' % DIRN

        try:
            f.retrbinary('RETR %s' % VERSION_FILE, open(os.path.dirname(sys.argv[0]) + '\\' + VERSION_FILE_TEMP, 'wb').write)
            
            if self.checkVersion() == True :
                ######print 'update'
               
                #self.waitingForUpdate()     
                           
                global DOWNLOAD_COUNT, fileSize, fileSave, dowloading
                DOWNLOAD_COUNT = 0.0
                fileSize = f.size(FILE)
                ######print fileSize
                fileSave = open(os.path.dirname(sys.argv[0]) + '\\' + FILE, 'wb')
                f.retrbinary('RETR %s' % FILE, self.handleDownload)
                fileSave.close()            
                self.updatedlg.Close()
                ######print 'confirmUpdate'
                self.confirmUpdate()
                
                
            else:
                self.notNewVersion1()
                self.updatedlg.Close()
                self.stop()
                
                        
                
        except ftplib.error_perm:
            wx.MessageBox("Cannot read file update", "Notification1", wx.OK)
            self.updatedlg.Destroy()
            ######print 'ERROR: cannot read file "%s"' % FILE
            #self.master.enableMenu()
            os.unlink(FILE)
#        else:
            
            ######print '*** Downloaded "%s" to CWD' % FILE
        f.quit()
        
        return rs

    
    #get current derectory
    def currentDer(self):
        ######print "currentDer: "+os.getcwd()
        return os.getcwd().replace('\\', '/')

    def confirmUpdate(self):
       
        #dlg = wx.MessageDialog(self.master,"Do you want to update the new version ?", 'Notification', wx.YES_NO | wx.ICON_QUESTION)
        #if dlg.ShowModal() == wx.ID_YES:
            self.onUpdateOK()
#        else:
            ######print "ko lam gi het"
            #self.openApp
            
    
    def onUpdateOK(self):
        try:
            ######print 'onUpdate'
            #self.waitingForUnzip()
            self.openUpdate()
            #dowloading.mainloop()
            #self.openApp()
        except Exception , inst:
            pass
            ######print inst
        
    def openUpdate(self):
        temp = os.path.dirname(sys.argv[0]).replace("\\", "/") + "/" + UPDATE_FILE
        ######print "openUpdate: "+temp
        subprocess.call(temp)
        
        
    #unzip file upload .zip
    def unzipfile(self):
        currentDers = self.currentDer()
        currentDers = currentDers + '/'
        ######print currentDers
        rs = False
        global  persent, var, f, FILE
        FILE = 'SSHClient.zip'
        try :
            ######print currentDers+FILE
            zf = zipfile.ZipFile(currentDers + FILE)
            i = 0
            ######print '1'
            for name in zf.namelist():
                #currentSize = f.size(currentDers+FILE)
                ######print name
                if  (name.endswith("/") and (name != APP_NAME)):
                    ######print name
                    if not os.path.exists(currentDers + name):
                        os.mkdir(currentDers + name)
                else:
                    try:
                        #######print name 
                        #######print 'b'
                        #os.remove(os.path.join(currentDers,name))
                        ######print 'b'
                        outfile = open(os.path.join(currentDers, name), 'wb')
                        outfile.write(zf.read(name))
                    except Exception , inst:
                        pass
                        ######print "unzip: "+str(inst)
                    
                i = i + 1
                #currentsize = os.path.getsize(currentDers+APP_NAME)
                #var.set("Extracting "+currentsize)
                #persent.create_rectangle(currentsize, 0, 0, 25, fill = "green")
                #dowloading.update()
                
            rs = True
                       
        except  Exception , inst:
            pass
            ######print inst

        #dowloading.destroy()
        #self.openApp()
        return rs
    
    def handleDownload(self, block):
        if not self.flag:
            return
        try:
            
            global DOWNLOAD_COUNT, fileSize, fileSave, dowloading, persent, var
            DOWNLOAD_COUNT += len(block)
            ######print 'tuan'
            ######print DOWNLOAD_COUNT                     
            
            fileSave.write(block)
               
            ######print fileSize
             
            per = "%d" % (round((DOWNLOAD_COUNT / fileSize) * 100))
            self.updatedlgstatic.SetLabel("Downloading for updating " + per + "%")            
            self.updatedlggauge.SetValue(int(per))
            #self.updatedlg.Update()
        except Exception , inst:
            pass
            ######print inst
    
    def waitingForUpdate(self):
        pass
        '''global dowloading, persent, var
        dowloading = Tkinter.Tk()
        dowloading.title("Download")
        var = Tkinter.StringVar()
        label = Tkinter.Label(textvariable=var)
        var.set("Downloading for updating")
        label.grid()
        persent = Tkinter.Canvas(borderwidth = 0, width = 400, height = 23)
        persent.grid()
        Tkinter.Label(height=1).grid()
        Tkinter.Button(text="Cancel", command = self.cancelUpdate ).grid()
        Tkinter.Label(height=1).grid()'''

    def notNewVersion1(self):
        try:        
            dlg = wx.MessageDialog(self.updatedlg, "Non new version !", 'Notification', wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
        except Exception, e:
            pass
            ######print type(e)
            ######print e
    #check version
    def checkVersion(self):
        rs = False
        try:
            oldVersion = self.getCurrentVersion()
            newVersion = self.getNewVersion()
            if oldVersion < newVersion :
                rs = True
               
        except Exception , inst:
            wx.MessageBox("Cannot read file update", "Notification", wx.OK)
            self.updatedlg.Destroy()
            
            #self.master.enableMenu()
            os.unlink(FILE)
                
        return rs

            
    #get current version by file
    def getCurrentVersion(self):
        
        myfile = open(os.path.dirname(sys.argv[0]) + '\\' + VERSION_FILE, 'r')
        myVersion = myfile.readline()
        myfile.close()
        return myVersion

    #get new version by file
    def getNewVersion(self):
        myfile = open(os.path.dirname(sys.argv[0]) + '\\' + VERSION_FILE_TEMP, 'r')
        myVersion = myfile.readline()
        myfile.close()
        return myVersion
    

    def killUpdate(self):
        WMI = GetObject('winmgmts:')
        processes = WMI.InstancesOf('Win32_Process')
        for proc in processes:
            if proc.Properties_("Name").Value == UPDATE_FILE:
                proc.Terminate

    def run(self):
        ######print 'run'
    
#    dlg = wx.MessageDialog(self.master,"Do you want to update the new version ?", 'Notification', wx.YES_NO | wx.ICON_QUESTION)
#    if dlg.ShowModal() == wx.ID_YES:
#        self.CreateUpdateDlg()
        try:
            self.downloadUpdateFile()
        except:
            self.stop()
            #pass
         
    def stop(self):
        self._running = False 

class MyListCtrl(wx.ListCtrl, listmix.ColumnSorterMixin):
    def __init__(self, parent,columns, ID, pos=wx.DefaultPosition,size=wx.DefaultSize, style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        listmix.ColumnSorterMixin.__init__(self,columns)
        
    def GetListCtrl(self):
        return self

class TranferFileDlg(threading.Thread, wx.Frame):
    def __init__(self, master):
        try:
            wx.Frame.__init__(self, master, -1, 'File Transfer Dialog', size=(740, 780),style=wx.FRAME_FLOAT_ON_PARENT | wx.CAPTION | wx.CLOSE_BOX  | wx.SYSTEM_MENU)
            self.Center()
            self.callback = None
            
            
            #Create menubar & statusbar
            self.master = master
            self.ftp = self.master.channel.get_transport().open_sftp_client()
            #Create panel
            self.panel = wx.Panel(self,-1)
            self.box = wx.BoxSizer(wx.VERTICAL)
            self.panel.SetSizer(self.box)
            self.panel.SetAutoLayout(True)
            
            #Create area
            wx.StaticLine(self.panel, -1, pos=(728,3),size=(3,415),style=wx.LI_VERTICAL)#doc-phai
            wx.StaticLine(self.panel, -1, pos=(5,3),size=(724,3),style=wx.LI_VERTICAL)#ngang-tren
            wx.StaticLine(self.panel, -1, pos=(5,415),size=(724,3),style=wx.LI_VERTICAL)#ngang-duoi
            wx.StaticLine(self.panel, -1, pos=(3,3),size=(3,415),style=wx.LI_VERTICAL)#doc-trai
            wx.StaticLine(self.panel, -1, pos=(363,3),size=(3,415),style=wx.LI_VERTICAL)#doc-giua
            
            wx.StaticLine(self.panel, -1, pos=(728,430),size=(3,283),style=wx.LI_VERTICAL)##doc-phai
            wx.StaticLine(self.panel, -1, pos=(5,710),size=(724,3),style=wx.LI_VERTICAL)##ngang-duoi
            wx.StaticLine(self.panel, -1, pos=(5,430),size=(12,3),style=wx.LI_VERTICAL)#ngang-tren-1
            wx.StaticLine(self.panel, -1, pos=(100,430),size=(629,3),style=wx.LI_VERTICAL)#ngang-tren-2
            wx.StaticLine(self.panel, -1, pos=(3,430),size=(3,283),style=wx.LI_VERTICAL)#doc-trai
            #Create control
            #Choice
            sampleList = ['LOCAL MACHINE', 'REMOTE MACHINE']
            self.choiLeft = wx.Choice(self.panel, -1, (10,10),(345, 50), choices = sampleList)
            self.choiLeft.SetSelection(0)
            self.Bind(wx.EVT_CHOICE  , self.OnChoiLeft,self.choiLeft)            
            self.diskLeft = wx.Choice(self.panel, -1, (10,100),(160, 50))
            self.Bind(wx.EVT_CHOICE  , self.OnDiskLeft,self.diskLeft)
            self.choiRight = wx.Choice(self.panel, -1, (375,10),(345, 50), choices = sampleList)
            self.choiRight.SetSelection(1)
            self.Bind(wx.EVT_CHOICE  , self.OnChoiRight,self.choiRight)
            self.diskRight = wx.Choice(self.panel, -1, (375,40),(160, 50))
            self.Bind(wx.EVT_CHOICE  , self.OnDiskRight,self.diskRight)
            
            self.choiHistory = wx.Choice(self.panel, -1, (10,682),(710,170))
            #TextCtrl
            self.tctrlLeft = wx.TextCtrl(self.panel, -1, "", (180,40),(176, 23))
            self.tctrlLeft.SetEditable(False)            
            self.tctrlRight = wx.TextCtrl(self.panel, -1, "", (545,40),(176, 23))
            self.tctrlRight.SetEditable(False)
            self.tctrlSpeed = wx.TextCtrl(self.panel, -1, "", (630,475),(90, 23))
            self.tctrlSpeed.SetEditable(False)

            #Image Button
            bmp = wx.Bitmap("image/add.bmp", wx.BITMAP_TYPE_BMP)
            #bmp = wx.Bitmap("image/add.png", wx.BITMAP_TYPE_PNG)
            mask = wx.Mask(bmp, wx.BLUE)
            bmp.SetMask(mask)
            self.add_left = wx.BitmapButton(self.panel, -1, bmp, (10, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.add_right = wx.BitmapButton(self.panel, -1, bmp, (680, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.Bind(wx.EVT_BUTTON, self.OnNewFolder_Left, self.add_left)
            self.Bind(wx.EVT_BUTTON, self.OnNewFolder_Right, self.add_right)
            
            bmp = wx.Bitmap("image/delete.bmp", wx.BITMAP_TYPE_BMP)
            mask = wx.Mask(bmp, wx.BLUE)
            bmp.SetMask(mask)
            self.del_left = wx.BitmapButton(self.panel, -1, bmp, (50, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.del_right = wx.BitmapButton(self.panel, -1, bmp, (640, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.Bind(wx.EVT_BUTTON, self.OnDelete_Left, self.del_left)
            self.Bind(wx.EVT_BUTTON, self.OnDelete_Right, self.del_right)
            
            bmp = wx.Bitmap("image/desktop.bmp", wx.BITMAP_TYPE_BMP)
            mask = wx.Mask(bmp, wx.BLUE)
            bmp.SetMask(mask)
            self.desktop_left = wx.BitmapButton(self.panel, -1, bmp, (90, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.desktop_right = wx.BitmapButton(self.panel, -1, bmp, (600, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.Bind(wx.EVT_BUTTON, self.OnDesktop_Left, self.desktop_left)
            self.Bind(wx.EVT_BUTTON, self.OnDesktop_Right, self.desktop_right)
            
            bmp = wx.Bitmap("image/mydocuments.bmp", wx.BITMAP_TYPE_BMP)
            mask = wx.Mask(bmp, wx.BLUE)
            bmp.SetMask(mask)
            self.doc_left = wx.BitmapButton(self.panel, -1, bmp, (130, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.doc_right = wx.BitmapButton(self.panel, -1, bmp, (560, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.Bind(wx.EVT_BUTTON, self.OnDocument_Left, self.doc_left)
            self.Bind(wx.EVT_BUTTON, self.OnDocument_Right, self.doc_right)
            
            bmp = wx.Bitmap("image/rename.bmp", wx.BITMAP_TYPE_BMP)
            mask = wx.Mask(bmp, wx.BLUE)
            bmp.SetMask(mask)
            self.rename_left = wx.BitmapButton(self.panel, -1, bmp, (170, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.rename_right = wx.BitmapButton(self.panel, -1, bmp, (520, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.Bind(wx.EVT_BUTTON, self.OnRename_Left, self.rename_left)
            self.Bind(wx.EVT_BUTTON, self.OnRename_Right, self.rename_right)
            
            bmp = wx.Bitmap("image/send.bmp", wx.BITMAP_TYPE_BMP)
            mask = wx.Mask(bmp, wx.BLUE)
            bmp.SetMask(mask)
            self.send_left = wx.BitmapButton(self.panel, -1, bmp, (210, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.Bind(wx.EVT_BUTTON, self.OnSend_Left, self.send_left)
            
            bmp = wx.Bitmap("image/revice.bmp", wx.BITMAP_TYPE_BMP)
            mask = wx.Mask(bmp, wx.BLUE)
            bmp.SetMask(mask)
            self.revice_right = wx.BitmapButton(self.panel, -1, bmp, (480, 70),(bmp.GetWidth(), bmp.GetHeight()))
            self.Bind(wx.EVT_BUTTON, self.OnSend_Right, self.revice_right)
            
            bmp = wx.Bitmap("image/close1.bmp", wx.BITMAP_TYPE_BMP)
            mask = wx.Mask(bmp, wx.BLUE)
            bmp.SetMask(mask)
            self.btclose = wx.BitmapButton(self.panel, -1, bmp, (640, 715),(bmp.GetWidth(), bmp.GetHeight()))
            self.Bind(wx.EVT_BUTTON, self.OnClose, self.btclose)
            
            #Create listcontrol
            self.il = wx.ImageList(16,16)
            #self.image = wx.Bitmap("image/file.png", wx.BITMAP_TYPE_PNG)
            self.il.Add(wx.Bitmap("image/file.png", wx.BITMAP_TYPE_PNG))
            self.il.Add(wx.Bitmap("image/folder.png", wx.BITMAP_TYPE_PNG))
            #self.idx2 = self.il.Add(self.image2)
            
            
            self.listctrl_left = MyListCtrl(self.panel,3, -1,style=wx.LC_REPORT | wx.LC_VRULES | wx.LC_HRULES | wx.LC_SORT_ASCENDING, pos =(10,110),size = (345,280))
            self.listctrl_left.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
#            self.listctrl_left.InsertColumn(0, "File Name", width = 230)
#            self.listctrl_left.InsertColumn(1, "Size",width = 50)
#            self.listctrl_left.InsertColumn(2, "Modified",width = 100)
            self.listctrl_left.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False, 'Verdana'))
            self.listctrl_left.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectItemLeft)
            self.listctrl_left.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClickLeft)

            self.listctrl_right = MyListCtrl(self.panel,3, -1,style=wx.LC_REPORT | wx.LC_VRULES | wx.LC_HRULES | wx.LC_SORT_ASCENDING, pos =(375,110),size = (345,280))
            self.listctrl_right.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
#            self.listctrl_right.InsertColumn(0, "File Name", width = 230)
#            self.listctrl_right.InsertColumn(1, "Size",width = 50)
#            self.listctrl_right.InsertColumn(2, "Modified",width = 100)
            self.listctrl_right.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False, 'Verdana'))
            self.listctrl_right.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectItemRight)
            self.listctrl_right.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClickRight)
            
            self.listctrl_bottom = MyListCtrl(self.panel,4, -1,style=wx.LC_REPORT | wx.LC_VRULES | wx.LC_HRULES | wx.LC_SORT_ASCENDING, pos =(10,505),size = (710,170))
            self.listctrl_bottom.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
#            self.listctrl_bottom.InsertColumn(0, "Local Files", width = 230)
#            self.listctrl_bottom.InsertColumn(1, "",width = 50)
#            self.listctrl_bottom.InsertColumn(2, "Remote Files",width = 230)
#            self.listctrl_bottom.InsertColumn(3, "File size",width = 100)
            self.listctrl_bottom.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False, 'Verdana'))
            self.listctrl_bottom.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectItemBottom)
            self.listctrl_bottom.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClickBottom)
            

#            self.Bind(wx.EVT_CLOSE, self.OnExit)
#
#            self.listctrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.SelectedItem)
#            self.listctrl.Bind(wx.EVT_LEFT_DCLICK, self.OnConnect)
            
            
            #Static Text
            self.numFile_left = StaticText(self.panel, -1, "xx Folder(s) - xx File(s)", (90, 395), (160, -1), wx.ALIGN_RIGHT)
            self.numFile_right = StaticText(self.panel, -1, "xx Folder(s) - xx File(s)", (450, 395), (160, -1), wx.ALIGN_RIGHT)
            StaticText(self.panel, -1, "File:", (12, 457), (30, -1), wx.ALIGN_LEFT)
            StaticText(self.panel, -1, "xx%", (590, 478), (30, -1), wx.ALIGN_LEFT)
            text = StaticText(self.panel, -1, "Progress", (18, 420), (30, -1), wx.ALIGN_LEFT)
            font = wx.Font(14, wx.SWISS, wx.NORMAL, wx.NORMAL)
            text.SetFont(font)
            self.ipremote = StaticText(self.panel, -1, "Remote Machine: x.x.x.x", (10, 730), (200, -1), wx.ALIGN_LEFT)
            #Button
            self.btremove = wx.Button(self.panel,-1,"Remove",(585,445),(65,25))
            self.btcancel = wx.Button(self.panel,-1,"Cancel",(655,445),(65,25))
            
            #Gauge
            self.gauge = wx.Gauge(self.panel, -1, 100, (10, 475), (575, 25))

            # setting
            icon = wx.Icon("image/house_16.ico", wx.BITMAP_TYPE_ICO, 16, 16)
            self.SetIcon(icon)
            
            #Event
            self.Bind(wx.EVT_CLOSE, self.OnExit)
            
            self.LoadData(1)
            self.LoadData(2)
            
        except Exception, e:
            ######print type(e)
            print e
            return
    #event button
    def OnNewFolder_Left(self,event):
        pass
    def OnNewFolder_Right(self,event):
        pass
    def OnRename_Left(self,event):
        pass
    def OnRename_Right(self,event):
        pass
    def OnDelete_Left(self,event):
        pass
    def OnDelete_Right(self,event):
        pass
    def OnDesktop_Left(self,event):
        pass
    def OnDesktop_Right(self,event):
        pass
    def OnDocument_Left(self,event):
        pass
    def OnDocument_Right(self,event):
        pass
    def OnSend_Left(self,event):
        pass
    def OnSend_Right(self,event):
        pass
    def OnRemove(self,event):
        pass
    def OnCancel(self,event):
        pass
    def OnClose(self,event):
        pass
    
    def OnChoiLeft(self,event):
        self.LoadData(1)
        pass
    def OnChoiRight(self,event):
        self.LoadData(2)
        pass
    def OnDiskLeft(self,event):
        self.tctrlLeft.Clear()
        self.listctrl_left.ClearAll()
        path = self.diskLeft.GetStringSelection()[:3]
        self.tctrlLeft.write(path)
        self.Show_ListFile(1)
        pass
    def OnDiskRight(self,event):
        self.tctrlRight.Clear()
        self.listctrl_right.ClearAll()
        path = self.diskRight.GetStringSelection()[:3]
        self.tctrlRight.write(path)
        self.Show_ListFile(2)
        pass
    
    def OnSelectItemLeft(self, evt):
        self.currentItemLeft = evt.m_itemIndex
        
    def OnDoubleClickLeft(self, event):
        try:     
            if self.listctrl_left.GetItemData(self.currentItemLeft)==0:
                self.changeCurrentPath(1,"", flagBack = 1)
                self.Show_ListFile(1)
                event.Skip()                        
            elif self.listctrl_left.GetItemData(self.currentItemLeft)==1:
                self.changeCurrentPath(1,self.listctrl_left.GetItemText(self.currentItemLeft))
                self.Show_ListFile(1)
                event.Skip()
        except Exception,e:
            print e
            wx.MessageBox(str(e), "Error", wx.OK, self)
            
        
        
    def OnSelectItemRight(self, evt):
        self.currentItemRight = evt.m_itemIndex
        
    def OnDoubleClickRight(self, event):     
        try:
            if self.listctrl_right.GetItemData(self.currentItemRight)==0:
                self.changeCurrentPath(2,"", flagBack = 1)
                self.Show_ListFile(2)
                event.Skip()                        
            elif self.listctrl_right.GetItemData(self.currentItemRight)==1:
                self.changeCurrentPath(2,self.listctrl_right.GetItemText(self.currentItemRight))
                self.Show_ListFile(2)
                event.Skip()
        except Exception,e:
            print e
            wx.MessageBox(str(e), "Error", wx.OK, self)

    

        
        
    def OnSelectItemBottom(self, evt):
        self.currentItemBottom = evt.m_itemIndex
        
    def OnDoubleClickBottom(self, event):     
        if self.list.GetItemData(self.currentItem)==1:
            self.changeCurrentPath(self.list.GetItemText(self.currentItem))
        elif self.list.GetItemData(self.currentItem)==3:
            self.changeCurrentPath("", flagBack = 1)
        else:
            self.loadFile(self.list.GetItemText(self.currentItem))   
        event.Skip()
        
    def changeCurrentPath(self, side, folder, flagBack = 0):
        if side == 1:
            if self.choiLeft.GetSelection() == 0:#Local Machine
                if flagBack!=0:
                    path = self.tctrlLeft.GetValue()[:-1]
                    self.tctrlLeft.SetValue(path[0:path.rfind("\\")+1]) 

                else:
                    path = self.tctrlLeft.GetValue()
                    self.tctrlLeft.SetValue(path + folder + "\\")
            else:
                if flagBack!=0:
                    if self.tctrlLeft.GetValue().rfind("/") == -1:
                        self.tctrlLeft.SetValue("")
                    else:
                        self.tctrlLeft.SetValue(self.tctrlLeft.GetValue()[0:self.tctrlLeft.GetValue().rfind("/")])
                    
                elif self.tctrlLeft.GetValue()!="":
                    self.tctrlLeft.SetValue(self.tctrlLeft.GetValue()+"/"+str(folder)) 
                    
                else:
                    self.tctrlLeft.SetValue(str(folder))
        else:
            if self.choiRight.GetSelection() == 0:#Local Machine
                if flagBack!=0:
                    path = self.tctrlRight.GetValue()[:-1]
                    self.tctrlRight.SetValue(path[0:path.rfind("\\")+1]) 

                else:
                    path = self.tctrlRight.GetValue()
                    self.tctrlRight.SetValue(path + folder + "\\")
            else:
                if flagBack!=0:
                    if self.tctrlRight.GetValue().rfind("/") == -1:
                        self.tctrlRight.SetValue("")
                    else:
                        self.tctrlRight.SetValue(self.tctrlRight.GetValue()[0:self.tctrlRight.GetValue().rfind("/")])
                    
                elif self.tctrlRight.GetValue()!="":
                    self.tctrlRight.SetValue(self.tctrlRight.GetValue()+"/"+str(folder)) 
                    
                else:
                    self.tctrlRight.SetValue(str(folder))
    
    def Load_Drives(self,side):
        L = []
        if side == 1:
            if self.choiLeft.GetSelection() == 0:#Window
                DRIVE_TYPES = ['Unknown','No Root Directory','Removable Disk','Local Disk','Network Drive','Compact Disc','RAM Disk']
                drives = (drive for drive in win32api.GetLogicalDriveStrings ().split ("\000") if drive)
                for drive in drives:
                    L.append(drive + "    " + DRIVE_TYPES[win32file.GetDriveType (drive)])
                return L
            else:#Unix
                pass
        else:
            if self.choiRight.GetSelection() == 0:#Window
                DRIVE_TYPES = ['Unknown','No Root Directory','Removable Disk','Local Disk','Network Drive','Compact Disc','RAM Disk']
                drives = (drive for drive in win32api.GetLogicalDriveStrings ().split ("\000") if drive)
                for drive in drives:
                    L.append(drive + "    " + DRIVE_TYPES[win32file.GetDriveType (drive)])
                return L
            else:#Unix
                pass
    
    def SizeToString(self,size):
        if size <= 1023:
            return "%0.0f Bytes" % (size)
        elif size <= 1023*1024:
            return "%0.1f KB" % (size/1024.0)
        elif size <= 1023*1024*1024:
            return "%0.1f MB" % (size/(1024*1024.0))
        elif size >= 1023*1024*1024:
            return "%0.1f GB" % (size/(1024*1024*1023.0))
    
    def is_public(self, text):
        return text.rfind(":")!=-1;
    
    def is_file(self,first):
        if(len(first)>0):
            if (first[0]=='d'):
                return False;
        return True;
    
    def Load_ListFile(self,side):
        L = []
        if side == 1:
            path = self.tctrlLeft.GetValue()
            if self.choiLeft.GetSelection() == 0:
                dirList=os.listdir(path)
                for fname in dirList:
                    spath = path + fname
                    if os.path.isdir(spath):
                        L.append((fname,"Folder",time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(spath)))))
                    else:
                        L.append((fname,self.SizeToString(os.path.getsize(spath)),time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(spath)))))
                return L
            else:
                if path != "":
                    files = self.ftp.listdir_attr(path)
                else:
                    files = self.ftp.listdir_attr()
                for lin in files:
                #lin = lin.decode(wx.GetDefaultPyEncoding(), 'ignore')
                    if self.is_public(str(lin).split()[7]):
                        first = str(lin).split()[0]
                        if self.is_file(first):
                            L.append((lin.filename,self.SizeToString(lin.st_size),time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(lin.st_mtime))))
                        else:
                            L.append((lin.filename,"Folder",time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(lin.st_mtime))))
                return L
        else:
            path = self.tctrlRight.GetValue()
            if self.choiRight.GetSelection() == 0:
                dirList=os.listdir(path)
                for fname in dirList:
                    spath = path + fname
                    if os.path.isdir(spath):
                        L.append((fname,"Folder",time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(spath)))))
                    else:
                        L.append((fname,self.SizeToString(os.path.getsize(spath)),time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(spath)))))
                return L
            else:
                if path != "":
                    files = self.ftp.listdir_attr(path)
                else:
                    files = self.ftp.listdir_attr()
                for lin in files:
                #lin = lin.decode(wx.GetDefaultPyEncoding(), 'ignore')
                    if self.is_public(str(lin).split()[7]):
                        first = str(lin).split()[0]
                        if self.is_file(first):
                            L.append((lin.filename,self.SizeToString(lin.st_size),time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(lin.st_mtime))))
                        else:
                            L.append((lin.filename,"Folder",time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(lin.st_mtime))))
                return L
    def Show_ListFile(self,side):
        if side == 1:
            try:
                path = self.tctrlLeft.GetValue()
                files = self.Load_ListFile(side)
#                if self.choiLeft.GetSelection() == 0:
#                    files = self.Load_ListFile(side)
#                else:
#                    files = self.Load_ListFile(side)
                self.listctrl_left.ClearAll()    
                self.listctrl_left.SetImageList(self.il,wx.IMAGE_LIST_SMALL)
                self.listctrl_left.InsertColumn(0, "File name", format = LIST_FORMAT_LEFT)
                self.listctrl_left.InsertColumn(1, "Size", format = LIST_FORMAT_RIGHT)
                self.listctrl_left.InsertColumn(2, "Modified", format = LIST_FORMAT_CENTER)
                self.listctrl_left.SetColumnWidth(0,150)
                self.listctrl_left.SetColumnWidth(1,100)
                self.listctrl_left.SetColumnWidth(2,150)
                self.listctrl_left.itemDataMap = files
                
                if self.choiLeft.GetSelection() == 0:
                    if len(path.split("\\"))>2: 
                        index = self.listctrl_left.InsertImageStringItem(sys.maxint, "[...]",1)
                        self.listctrl_left.SetItemData(index, 0)            
                else:
                    if path != "": 
                        index = self.listctrl_left.InsertImageStringItem(sys.maxint, "[...]",1)
                        self.listctrl_left.SetItemData(index, 0)
               
                numfile = 0
                numfolder = 0    
                for file in files:
                    name = file[0]
                    size = file[1]
                    modified = file[2]
                    if size == "Folder":
                        index = self.listctrl_left.InsertImageStringItem(sys.maxint, name, 1)
                        self.listctrl_left.SetItemData(index, 1)
                        numfolder += 1
                    else:
                        index = self.listctrl_left.InsertImageStringItem(sys.maxint, name, 0)
                        self.listctrl_left.SetItemData(index, 2)
                        numfile += 1
                    self.listctrl_left.SetStringItem(index, 1, size)
                    self.listctrl_left.SetStringItem(index, 2, modified)
                self.listctrl_left.SortListItems(0, True)
                self.numFile_left.SetLabel(str(numfolder) + " Folder(s) - " + str(numfile) + " File(s)")
                pass;
            except Exception,e:
                if type(e) == WindowsError:
                    self.changeCurrentPath(1,"", flagBack = 1)

                print e
#                wx.MessageBox(str(e), "Error", wx.OK, self)
        else:
            try:
                path = self.tctrlRight.GetValue()
                files = self.Load_ListFile(side)
#                if self.choiRight.GetSelection() == 0:
#                    files = self.Load_ListFile(side)
#                else:
#                    files = self.Load_ListFile(side)
                self.listctrl_right.ClearAll()    
                self.listctrl_right.SetImageList(self.il,wx.IMAGE_LIST_SMALL)
                self.listctrl_right.InsertColumn(0, "File name", format = LIST_FORMAT_LEFT)
                self.listctrl_right.InsertColumn(1, "Size", format = LIST_FORMAT_RIGHT)
                self.listctrl_right.InsertColumn(2, "Modified", format = LIST_FORMAT_CENTER)
                self.listctrl_right.SetColumnWidth(0,150)
                self.listctrl_right.SetColumnWidth(1,100)
                self.listctrl_right.SetColumnWidth(2,150)
                self.listctrl_right.itemDataMap = files
                
                if self.choiRight.GetSelection() == 0:
                    if len(path.split("\\"))>2: 
                        index = self.listctrl_right.InsertImageStringItem(sys.maxint, "[...]",1)
                        self.listctrl_right.SetItemData(index, 0)            
                else:
                    if path != "": 
                        index = self.listctrl_right.InsertImageStringItem(sys.maxint, "[...]",1)
                        self.listctrl_right.SetItemData(index, 0)
               
                numfile = 0
                numfolder = 0    
                for file in files:
                    name = file[0]
                    size = file[1]
                    modified = file[2]
                    if size == "Folder":
                        index = self.listctrl_right.InsertImageStringItem(sys.maxint, name, 1)
                        self.listctrl_right.SetItemData(index, 1)
                        numfolder += 1
                    else:
                        index = self.listctrl_right.InsertImageStringItem(sys.maxint, name, 0)
                        self.listctrl_right.SetItemData(index, 2)
                        numfile += 1
                    self.listctrl_right.SetStringItem(index, 1, size)
                    self.listctrl_right.SetStringItem(index, 2, modified)
                self.listctrl_right.SortListItems(0, True)
                self.numFile_right.SetLabel(str(numfolder) + " Folder(s) - " + str(numfile) + " File(s)")
                pass;
            except Exception,e:
                if type(e) == WindowsError:
                    self.changeCurrentPath(2,"", flagBack = 1)
                print e
#                wx.MessageBox(str(e), "Error", wx.OK, self)
    
    def LoadData(self,side):
        if side == 1:#Ben Trai
            self.diskLeft.Clear()
            self.tctrlLeft.Clear()
            self.listctrl_left.ClearAll()
            if self.choiLeft.GetSelection() == 0:#Local Machine
                self.diskLeft.AppendItems(self.Load_Drives(side))
                self.diskLeft.Select(0)
                path = self.diskLeft.GetString(0)[:3]
                self.tctrlLeft.write(path)
                self.Show_ListFile(1)
                self.diskLeft.Enable(True)
                pass
            else:#Remote Machine
                path = ""
                self.tctrlLeft.write(path)
                self.Show_ListFile(1)
                self.diskLeft.Enable(False)
            pass
        else:#Ben Phai
            self.diskRight.Clear()
            self.tctrlRight.Clear()
            self.listctrl_right.ClearAll()
            if self.choiRight.GetSelection() == 0:#Local Machine                
                self.diskRight.AppendItems(self.Load_Drives(side))
                self.diskRight.Select(0)                
                path = self.diskRight.GetString(0)[:3]
                self.tctrlRight.write(path)
                self.Show_ListFile(2)
                self.diskRight.Enable(True)
                pass
            else:#Remote Machine
                path = ""
                self.tctrlRight.write(path)
                self.Show_ListFile(2)
                self.diskRight.Enable(False)                
            pass
               
    def OnExit(self, event):
        self.Destroy()
        self.result = event.EventObject.GetId()
        if self.callback <> None:
                self.callback()
                return
        
class NewOrEditDlg(threading.Thread, wx.Frame):
    def __init__(self, master, tp):
        try:
            if tp == 0:
                wx.Frame.__init__(self, master, -1, 'New Connection Dialog', size=(390, 300), style=wx.FRAME_FLOAT_ON_PARENT | wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU)
            else:
                wx.Frame.__init__(self, master, -1, 'Edit Connection Dialog', size=(390, 300), style=wx.FRAME_FLOAT_ON_PARENT | wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU)
            self.Center()
            self.master = master
            self.Bind(wx.EVT_CLOSE, self.OnExit)
            self.tp = tp
            
            self.panel = wx.Panel(self, -1)
            self.box = wx.BoxSizer(wx.VERTICAL)
            self.panel.SetSizer(self.box)
            self.panel.SetAutoLayout(True)

            font = wx.Font(13, wx.SWISS, wx.NORMAL, wx.NORMAL)
            
            str = "Name"
            text = StaticText(self.panel, -1, str, (63, 20), (300, -1))
            text.SetFont(font)
            self.ctrname = wx.TextCtrl(self.panel, -1, "", size=(200, 25) , pos=(140, 20))
  
            
            str = "HostName"
            text = StaticText(self.panel, -1, str, (30, 60), (160, -1), wx.ALIGN_RIGHT)
            text.SetFont(font)
            self.ctrhostname = wx.TextCtrl(self.panel, -1, "", size=(200, 25) , pos=(140, 60))
            
            str = "UserName"
            text = StaticText(self.panel, -1, str, (28, 100), (160, -1), wx.ALIGN_RIGHT)
            text.SetFont(font)
            self.ctrusername = wx.TextCtrl(self.panel, -1, "", size=(200, 25) , pos=(140, 100))

            str = "Password"
            text = StaticText(self.panel, -1, str, (31, 140), (160, -1), wx.ALIGN_RIGHT)
            text.SetFont(font)
            self.ctrpw = wx.TextCtrl(self.panel, -1, "", size=(200, 25) , pos=(140, 140), style=wx.TE_PASSWORD)

            #Create button
            self.butfont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
            self.butfont.SetPointSize(13)
            
            self.btsave = GB.GradientButton(self.panel, -1, None, "Save", size=(100, 35) , pos=(120, 200))
            self.btsave.SetTopStartColour(wx.Colour(0, 128, 192))
            self.btsave.SetTopEndColour(wx.Colour(0, 102, 151))
            self.btsave.SetBottomStartColour(wx.Colour(0, 102, 151))
            self.btsave.SetBottomEndColour(wx.Colour(0, 72, 106))
            self.btsave.SetPressedTopColour(wx.Colour(0, 128, 192))
            self.btsave.SetPressedBottomColour(wx.Colour(0, 124, 185))
            
            self.btconnect = GB.GradientButton(self.panel, -1, None, "Cancel", size=(100, 35) , pos=(240, 200))
            self.btconnect.SetTopStartColour(wx.Colour(0, 128, 192))
            self.btconnect.SetTopEndColour(wx.Colour(0, 102, 151))
            self.btconnect.SetBottomStartColour(wx.Colour(0, 102, 151))
            self.btconnect.SetBottomEndColour(wx.Colour(0, 72, 106))
            self.btconnect.SetPressedTopColour(wx.Colour(0, 128, 192))
            self.btconnect.SetPressedBottomColour(wx.Colour(0, 124, 185))

            self.btsave.SetFont(self.butfont)
            self.btconnect.SetFont(self.butfont)
            if tp == 0:            
                self.Bind(wx.EVT_BUTTON, self.OnSave, self.btsave)
                self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btconnect)
            else:
                self.ctrname.write(self.master.master.namecn)
                self.ctrhostname.write(self.master.master.hostnamecn)
                self.ctrusername.write(self.master.master.usernamecn)
                self.ctrpw.write(self.master.master.pwcn)
                self.Bind(wx.EVT_BUTTON, self.OnSave, self.btsave)
                self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btconnect)
                
            icon = wx.Icon("image/house_16.ico", wx.BITMAP_TYPE_ICO, 16, 16)
            self.SetIcon(icon)
               
        except Exception, e:
            ######print type(e)
            ######print e
            return
    
    
            
    def TestDataInput(self):
        self.namecn = self.ctrname.GetValue()
        self.hostcn = self.ctrhostname.GetValue()

        self.usernamecn = self.ctrusername.GetValue()
        self.passwordcn = self.ctrpw.GetValue()
        
        if len(self.namecn) == 0:
            wx.MessageBox("Please insert Name connection", "Error Input Name", wx.OK, self)
            return False
        for i in range(len(self.master.master.listconnections)):
            if self.master.master.listconnections[i][0] != self.master.master.namecn:
                if(self.master.master.listconnections[i][0] == self.namecn):
                    wx.MessageBox("The Name was exit !", "Error Input Name", wx.OK, self)
                    return False
        if len(self.hostcn) == 0:
            wx.MessageBox("Please insert Host connection", "Error Input Host", wx.OK, self)
            #tkMessageBox.showerror("Host","Please insert Host connection")
            return False
        elif len(self.usernamecn) == 0:
            wx.MessageBox("Please insert UserName connection", "Error Input UserName", wx.OK, self)
            #tkMessageBox.showerror("Username","Please insert Username connection")#
            return False
        elif len(self.passwordcn) == 0:
            wx.MessageBox("Please insert Password connection", "Error Input Password", wx.OK, self)
            #tkMessageBox.showerror("Password","Please insert Password connection")
            return False
        return True
        
    def OnSave(self, event):
        if not self.TestDataInput():
            return
        #process New
        if self.tp == 0:
            self.master.master.listconnections.append([self.namecn, self.hostcn, self.usernamecn, self.passwordcn])
            self.master.master.WriteFileConnection(True)
            self.master.LoadDataListCtrl()
#            wx.MessageBox("Create new connection successful", "Notice", wx.OK,self)
            self.master.master.currentItem = len(self.master.master.listconnections) - 1
            self.Close()
            ######print self.master.master.currentItem
#            answer = wx.MessageBox("Do you want conenct to this server ?", "Question", wx.YES_NO, self)
#            if answer == wx.YES:
#                self.Close()
#                ######print 'da vao day'
#                self.master.ProcessOpen()
#            else:
#                self.Close()
        #process Edit
        else:
            self.master.master.listconnections[self.master.master.currentItem] = [self.namecn, self.hostcn, self.usernamecn, self.passwordcn]
            self.master.master.WriteFileConnection(True)
            self.master.LoadDataListCtrl()
            self.Close()
#            wx.MessageBox("Edit connection successful", "Notice", wx.OK,self)
#            answer = wx.MessageBox("Do you want conenct to this server ?", "Question", wx.YES_NO, self)
#            if answer == wx.YES:
#                self.Close()
#                self.master.ProcessOpen()                
#            else:
#                self.Close()
            
    def OnCancel(self, event):
        self.Close()           

    def OnConnect(self, event):
        if not self.TestDataInput():
            return
        
        self.master.master.listconnections.append([self.namecn, self.hostcn, self.usernamecn, self.passwordcn])
        self.master.master.WriteFileConnection(True)
        self.master.LoadDataListCtrl()
        if self.tp == 0:
            self.master.master.currentItem = len(self.master.master.listconnections) - 1
        self.Close()
        self.master.ProcessOpen()
                    

    def OnExit(self, event):
        self.Destroy()
        self.result = event.EventObject.GetId()
        if self.callback <> None:
                self.callback()
                
class MessageDialogCustom(wx.Dialog):
    def __init__(self):
        pre = wx.PreDialog()


class SettingDlg(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.Frame.__init__(self, None, -1, "Setting", size=(600, 459), style = wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU )
        
        self.CenterOnParent()
        self.callback = None
        self.Bind(wx.EVT_CLOSE, self.closeDialog)
        
        self.panel = wx.Panel(self, -1)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.panel.SetSizer(self.sizer)
        
        wx.StaticText(self.panel, -1, "Catalog", (10,5), (300,-1))
        
        self.treebook = wx.Treebook(self.panel,-1, pos = (10,25),size=(570,399), style=
                             wx.BK_DEFAULT
                             
                            )
    
#        self.SendSizeEvent()
        
        panel1 = wx.Panel(self.treebook)
        panel2 = wx.Panel(self.treebook)
        panel3 = wx.Panel(self.treebook)
        panel4 = wx.Panel(self.treebook)
        panel5 = wx.Panel(self.treebook)
        
        panel11 = wx.Panel(self.treebook)
        panel12 = wx.Panel(self.treebook)
        panel13 = wx.Panel(self.treebook)
        panel14 = wx.Panel(self.treebook)
        panel15 = wx.Panel(self.treebook)
        panel16 = wx.Panel(self.treebook)
        
        panel111 = wx.Panel(self.treebook)
        
        panel121 = wx.Panel(self.treebook)
        panel122 = wx.Panel(self.treebook)
        panel123 = wx.Panel(self.treebook)
        
        panel21 = wx.Panel(self.treebook)
        panel22 = wx.Panel(self.treebook)
        panel23 = wx.Panel(self.treebook)
        
        panel41 = wx.Panel(self.treebook)
        panel42 = wx.Panel(self.treebook)
        
        panel31 = wx.Panel(self.treebook)
        
        self.treebook.AddPage(panel1, 'Connection', True)
        
        self.treebook.AddSubPage(panel11, 'Authentication')
        self.treebook.InsertSubPage(1,panel111, 'Login Prompt', True)
        
        self.treebook.AddSubPage(panel12, 'SSH', True)
        self.treebook.InsertSubPage(3,panel121, 'Security', True)
        self.treebook.InsertSubPage(3,panel122, 'Tunneling', True)
        self.treebook.InsertSubPage(3,panel123, 'SFTP', True)
        
        self.treebook.AddSubPage(panel13, 'TELNET', True)
        self.treebook.InsertSubPage(7,panel14, 'RLOGIN', True)
        self.treebook.InsertSubPage(7,panel15, 'SERIAL', True)
        self.treebook.InsertSubPage(7,panel16, 'Proxy', True)
        
        self.treebook.AddPage(panel2, 'Terminal')
        self.treebook.InsertSubPage(11,panel21, 'Keyboard', True)
        self.treebook.InsertSubPage(11,panel22, 'VT Modes', True)
        self.treebook.InsertSubPage(11,panel23, 'Advanced', True)
        
        self.treebook.AddPage(panel3, 'Appearance')
        self.treebook.InsertSubPage(15,panel31, 'Margins', True)
        
        self.treebook.AddPage(panel4, 'Advanced')
        self.treebook.InsertSubPage(17,panel41, 'Trace', True)
        self.treebook.InsertSubPage(17,panel42, 'Logging', True)
        
        self.treebook.AddPage(panel5, 'ZMODEN', True)
        
        tc = self.treebook.GetTreeCtrl()
        child, cookie = tc.GetFirstChild(tc.GetRootItem()) 
        while child.IsOk(): 
            tc.SetItemFont(child, wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False)) 
            self.setFontItem(tc, child)
            child,cookie = tc.GetNextChild(tc.GetRootItem(), cookie) 
            
        
        self.treebook.SetSelection(0)
         #pannel1
        connec = wx.StaticText(panel1, -1, "Connection", (10,0), (405,-1), wx.ALIGN_LEFT).SetBackgroundColour("White")
        staticBox = wx.StaticBox(panel1, -1, "General", (10,30), (405, 120))
        staticBox.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False))
        labelName = wx.StaticText( panel1, -1, "Name:", (20,50))
        labelName = wx.StaticText( panel1, -1, "Protocol:", (20,75))
        labelName = wx.StaticText( panel1, -1, "Host:", (20,100))
        labelName = wx.StaticText( panel1, -1, "Port Number:", (20,125))
        
        txt1 = wx.TextCtrl(panel1, -1,"", (100,50), (150,-1))
        choices = ["SSH"]
        combox = wx.ComboBox(panel1, -1, "", (100,75), (150,-1),choices, style = wx.CB_READONLY)
        txt2 = wx.TextCtrl(panel1, -1,"", (100,100), (150,-1))
        spin = wx.SpinCtrl(panel1, -1,"",(100,125), (150,-1 ))
        image = wx.Image("image/Monitors.gif", wx.BITMAP_TYPE_ANY)
        wx.StaticBitmap(panel1, -1, wx.BitmapFromImage(image),pos=(300,75), size=(16,16 ))
        
        spin.SetRange(1,100)
        spin.SetValue(1)
        
        staticBox =wx.StaticBox(panel1, -1,"Keep Alive", (10,150), (405,100))
        staticBox.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False))
        wx.CheckBox(panel1, -1,"Send", (20,170))
        wx.StaticText(panel1, -1,"Interval",(20,195) )
        spin = wx.SpinCtrl(panel1, -1, "", (100,195), (150,-1 ))
        wx.StaticText(panel1, -1,"sec.",(255,195) )
        wx.CheckBox(panel1, -1,"Send", (20,220))
        
        staticBox =wx.StaticBox(panel1, -1, "Reconnect", (10,250),(405,90))
        staticBox.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False))
        
    def  closeDialog(self, event):
        self.Destroy()
        #self.result = event.EventObject.GetId()
        if self.callback <> None:
                self.callback()    
    
    def setFontItem(self,tree,item):
        if tree.GetChildrenCount(item)>0:
            tree.SetItemFont(item, wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False))
            child, cookie = tree.GetFirstChild(item) 
            while child.IsOk(): 
                self.setFontItem(tree, child)
                child,cookie = tree.GetNextChild(child, cookie) 
        

class OpenDialogNP(threading.Thread, wx.Frame):    
    
    def __init__(self, parent):
        threading.Thread.__init__(self)
        self.parent = parent
            
        wx.Frame.__init__(self, None, -1, "Open file", size=(420, 600), style =  wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU )
        self.fontn = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, encoding=wx.FONTENCODING_DEFAULT)
        self.Center()
        self.callback = None
        self.Bind(wx.EVT_CLOSE, self.closeDialog)
        icon = wx.Icon("image/house_16.ico", wx.BITMAP_TYPE_ICO, 16, 16)
        self.SetIcon(icon)
        
        self.il = wx.ImageList(16, 16)
        self.bmFolder = self.il.Add(wx.Bitmap("image/open_small.png", wx.BITMAP_TYPE_PNG))
        self.bmFile = self.il.Add(wx.Bitmap("image/file.png", wx.BITMAP_TYPE_PNG))
        
        self.panel = wx.Panel(self, -1)
        self.panel.SetFont(self.fontn)
        # list
        self.list = wx.ListCtrl(self.panel, -1, size=(420,600) , style=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES|wx.LC_SORT_ASCENDING)
        self.list.SetFont(self.fontn)
        #bind
        self.list.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectItem)
        self.list.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
        self.start()
        
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.panel.SetSizer(self.sizer)
        self.panel.SetAutoLayout(True)
        self.sizer.Add(self.list, 1, wx.EXPAND)
        
        self.statusBar = self.CreateStatusBar()
        self.statusBar.SetFont(self.fontn)
        self.statusBar.SetFieldsCount(1)
        self.statusBar.sizeChanged = False
        self.statusBar.SetStatusWidths([420])
        self.statusBar.SetStatusText("./",0)
        self.SetAutoLayout(True)
             
    #itemdata: 2 (file) 1(folder)

    
    
    def loadFile(self, filename):
        self.closeDialog(None)   
        self.parent.readFile(filename)     
    
    def changeCurrentPath(self, folder, flagBack = 0):
        try:
            folder = folder.decode(wx.GetDefaultPyEncoding(), 'ignore')
            if flagBack!=0:
                if self.parent.ftp.getcwd().rfind("/") == -1:
                    self.parent.ftp.chdir(None)
                else:
                    self.parent.ftp.chdir(self.parent.ftp.getcwd()[0:self.parent.ftp.getcwd().rfind("/")])
                
            elif self.parent.ftp.getcwd()!=None:
                print self.parent.ftp.getcwd()
                self.parent.ftp.chdir(self.parent.ftp.getcwd() +"/"+ folder)
                
            else:
               
                self.parent.ftp.chdir(folder)
                
            self.start()
        except Exception, e:
            print folder
            print e
            print "changeCurrentPath"
            
            pass
        
    def changeCurrentPath1(self, folder, flagBack = 0):
        try:
            #folder = folder.decode(wx.GetDefaultPyEncoding(), 'ignore')
            if flagBack!=0:
                if self.parent.currentPath.rfind("/") == -1:
                    self.parent.currentPath = ""
                else:
                    self.parent.currentPath = self.parent.currentPath[0:self.parent.currentPath.rfind("/")]
                
            elif self.parent.currentPath!="":
                self.parent.currentPath = self.parent.currentPath+"/"+str(folder)
                
            else:
                self.parent.currentPath = str(folder)
                
            self.start()
        except Exception, e:
            if flagBack!=0:
                if self.parent.currentPath.rfind("/") == -1:
                    self.parent.currentPath = ""
                else:
                    self.parent.currentPath = self.parent.currentPath[0:self.parent.currentPath.rfind("/")]
                
            elif self.parent.currentPath!="":
                self.parent.currentPath = self.parent.currentPath+"/"+folder
                
            else:
                self.parent.currentPath = folder
                
            self.start()
            #wx.MessageBox("aa")
            
    
    def OnSelectItem(self, evt):
        self.currentItem = evt.m_itemIndex
        
    def OnDoubleClick(self, event):     
        if self.list.GetItemData(self.currentItem)==1:
            self.changeCurrentPath(self.list.GetItemText(self.currentItem))
        elif self.list.GetItemData(self.currentItem)==0:
            self.changeCurrentPath("", flagBack = 1)
        else:
            self.loadFile(self.list.GetItemText(self.currentItem))   
        event.Skip()
    
    def start(self):
        notepadReloadFolder = NotepadReloadFolder(self)
        notepadReloadFolder.start()
        
    def run(self):
        try:
            self.list.ClearAll()
            self.list.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
            #self.list.InsertImageStringItem(0 , , self.bmFolder)
            self.list.InsertColumn(0, "File name", format = LIST_FORMAT_LEFT)
            self.list.InsertColumn(1, "Size", format = LIST_FORMAT_RIGHT)
            self.list.InsertColumn(2, "Modified", format = LIST_FORMAT_CENTER)
            self.list.SetColumnWidth(0,190)
            self.list.SetColumnWidth(1,80)
            self.list.SetColumnWidth(2,140)
            filess = self.parent.ftp.listdir_attr()
            
#            if self.parent.currentPath!="":
#                filess = self.parent.ftp.listdir_attr(self.parent.currentPath)
#                self.statusBar.SetStatusText("./"+self.parent.currentPath,0)
#            else:
#                filess = self.parent.ftp.listdir_attr()
#                self.statusBar.SetStatusText("./",0)
            
            if self.parent.ftp.getcwd()!=None: 
                index = self.list.InsertImageStringItem(sys.maxint, "..", self.bmFolder)
                self.list.SetItemData(index, 0)
            
                
            self.list.Freeze()
            for lin in filess:
                
                temp = lin.__str__()
                
                if self.is_Show(lin.filename)== True:
                    first = temp[0]
                    name = lin.filename
                    size = lin.st_size/1024 
                    modified = self.convertTime(lin.st_mtime)            
                    #self.files.append([name, size, modified])
                    if self.is_file(first):
                        index = self.list.InsertImageStringItem(sys.maxint, name, self.bmFile)
                        self.list.SetItemData(index, 2)
                    else:
                        index = self.list.InsertImageStringItem(sys.maxint, name, self.bmFolder)
                        self.list.SetItemData(index, 1)
                    self.list.SetStringItem(index, 1, str(size)+" kb")
                    self.list.SetStringItem(index, 2, modified)
                    
            
            self.list.SortItems(self.mysort); 
            
        except Exception,e:
            if (self.list.IsFrozen()==True):
                self.list.Thaw()
            
            wx.MessageBox("Couldn't open the folder")
            if self.parent.ftp.getcwd()!=None:
                self.changeCurrentPath("", flagBack = 1)
            pass
        finally:
            try:
                if (self !="" and self.list.IsFrozen()==True):
                    self.list.Thaw()
            except Exception:
                return
            
    def is_Show(self, filename):
        if filename[0] != ".":
            filename = filename[filename.rfind("."):]
            if filename != ".png" or filename != ".jpg" or filename != ".gif" or filename != ".bmp":
                return True
        return False;
                
    
    def mysort(self, key1, key2):
        item1 = self.list.GetItem( self.list.FindItemData(-1, key1), 0)
        item2 = self.list.GetItem( self.list.FindItemData(-1, key2), 0)
        if ( item1.GetData() > item2.GetData() ):
            return 1; 
            
        elif ( item1.GetData() < item2.GetData() ): 
            return -1; 
        
        else:

            if ( item1.GetText() > item2.GetText() ):
                return 1; 
            else:
                return -1; 
                
    
    def is_file(self,first):
        return first!='d'
             
    def convertTime(self, mtime):
        return time.strftime("%Y/%m/%d %H:%M", time.localtime(mtime))
    
    def closeDialog(self, event):
        self.Destroy()
        #self.result = event.EventObject.GetId()
        if self.callback <> None:
                self.callback()

class NotepadReloadFolder(threading.Thread):
    def __init__(self, parent, mode=None):
        threading.Thread.__init__(self)
        self.parent = parent
        
    def run(self):
        self.parent.run()
        

class NotepadReadFile(threading.Thread):
    def __init__(self, parent, filename, mode=None):
        threading.Thread.__init__(self)
        self.parent = parent  
        self.filename = filename
        try:
            #self.parent.ftp.chdir(self.parent.currentPath)
            
            self.my_file = self.parent.ftp.open(self.filename, "r+")
        except Exception,e:
            print e
            print filename
            wx.MessageBox("Couldn't open the file")
        
    def run(self):
        try:
            self.parent.disableOpen()
            self.parent.disableSave()
             
            self.parent.text.Clear()
            for line in self.my_file:
                self.writeline(line)                
            
            self.parent.enableSave()  
        except Exception, e:
            self.parent.enableOpen()
            pass
        
        finally:
            self.parent.enableOpen()
            self.my_file.close()
    
    def writeline(self,data):
        data = data.decode(wx.GetDefaultPyEncoding(), 'ignore')
        self.parent.text.WriteText(data)        
        
        

class NotepadDlg(threading.Thread, wx.Frame):
    def __init__(self, master):
        try:
            self.master = master
            wx.Frame.__init__(self, None, -1, 'Notepad', size=(900, 700))
            self.fontn = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, encoding=wx.FONTENCODING_DEFAULT)
            self.callback = None
            self.Bind(wx.EVT_CLOSE, self.closeDialog)
            self.SetMinSize((650, 500))
            if master.channel!="":
                self.ftp = master.channel.get_transport().open_sftp_client()
                self.currentPath = ""
                #self.currentPath = self.ftp.getcwd()
            self.currentFile = ""    
            self.Center()
            
            self.open_bmp = wx.Bitmap("image/open.png", wx.BITMAP_TYPE_PNG)
            self.save_bmp = wx.Bitmap("image/save.png", wx.BITMAP_TYPE_PNG)
            
            #Create menuitem
            self.menuFile = wx.Menu()
            item = wx.MenuItem(self.menuFile, 1, "Open")
            item.SetBitmap(self.open_bmp)
            self.menuFile.AppendItem(item)
    
            item = wx.MenuItem(self.menuFile, 2, "Save")
            item.SetBitmap(self.save_bmp)
            self.menuFile.AppendItem(item)
            item.Enable(False)
            
            
            icon = wx.Icon("image/house_16.ico", wx.BITMAP_TYPE_ICO, 16, 16)
            self.SetIcon(icon)
            
            #Create menubar & statusbar
            self.menuBar = wx.MenuBar()
            self.menuBar.Append(self.menuFile, "File")
            
            self.SetMenuBar(self.menuBar)
            
            # event menu
            self.Bind(wx.EVT_MENU, self.menuOpen, id = 1)
            self.Bind(wx.EVT_MENU, self.saveFile, id = 2)
    
            self.panel = wx.Panel(self, -1)
            self.panel.SetFont(self.master.fontn)
            
            self.box = wx.BoxSizer(wx.VERTICAL)
            
            #self.box = wx.BoxSizer(wx.HORIZONTAL)
            self.panel.SetSizer(self.box)
            self.panel.SetAutoLayout(True)
            
        
            self.text = wx.TextCtrl(self.panel, -1, "Text Control\n", style=wx.TE_MULTILINE|wx.TE_RICH2)#|wx.HSCROLL)
            self.text.Bind(wx.EVT_CHAR, self.chageValue)
            self.text.Bind(wx.EVT_KEY_DOWN, self.chageValue)
            self.text.Bind(wx.EVT_TEXT_CUT, self.chageValue)
            self.text.Bind(wx.EVT_TEXT_PASTE, self.chageValue)
            
            self.text.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)
            self.text.SetFont(self.master.fontn)
            
            self.box.Add(self.text, 1, wx.EXPAND)
            
            self.text.SetFocus()
            #toolbar
            self.statusBar = self.CreateStatusBar()
            self.statusBar.SetFont(self.fontn)
            self.statusBar.SetFieldsCount(1)
            self.statusBar.sizeChanged = False
            self.statusBar.SetStatusWidths([900])
            self.statusBar.SetStatusText("./",0)
            
            
            
        except Exception, e:
            ######print type(e)
            ######print e
            return
        
    def chageValue(self, event):
        self.enableSave()
        event.Skip()
        
    def saveFile(self, event):
        try:
            filename = self.currentFile
            if self.currentPath!="":
                filename = self.currentPath + "/" + filename 
            
            my_file = self.ftp.open(filename, "w+")
            my_file.write(self.text.GetValue())
            my_file.close()
            self.disableSave()
            self.statusBar.SetStatusText("./",0)
            wx.MessageBox("Saving was successful")
        except Exception, e:
            print e
    
    def enableOpen(self):
        item = self.menuFile.FindItemById(1)
        item.Enable(True)
    
    def enableSave(self):
        item = self.menuFile.FindItemById(2)
        item.Enable(True)
        
    def disableOpen(self):
        item = self.menuFile.FindItemById(1)
        item.Enable(False)
    
    def disableSave(self):
        item = self.menuFile.FindItemById(2)
        item.Enable(False)
    
    def readFile(self,filename):
        #self.currentPath = filename
#        self.currentFile = filename
#        if self.currentPath!="":
#            filename = self.currentPath + "/" + filename
#            self.statusBar.SetStatusText("./"+filename, 0)
#        else:
#            self.statusBar.SetStatusText("./"+filename, 0)
#        
        try:    
            #filess = self.ftp.listdir_attr(self.currentPath)
            
            notepadReadFile = NotepadReadFile(self, filename)
            notepadReadFile.start()
        except Exception:
            pass
    
    def closeDialog(self, event):
        self.Destroy()
        self.result = event.EventObject.GetId()
        if self.callback <> None:
                self.callback()
        
    def menuOpen(self,event):
        if self.master.channel!="":
            self.ftp = self.master.channel.get_transport().open_sftp_client()
            self.currentPath = "";
        self.x = self.openDialog()
        self.x.next()
        
    def openDialog(self):
        self.Enable(False)
        openDialog = OpenDialogNP(self)
        openDialog.callback = self.x.next
        openDialog.CenterOnParent()
        openDialog.Show(True)
        openDialog.Raise()
        yield None
        self.Enable(True)
        self.text.SetFocus()
        yield None
        
        

    
class ConnectDlg(threading.Thread, wx.Frame):
    def __init__(self, master):
        try:
            wx.Frame.__init__(self, master, -1, 'Connect Dialog', size=(345, 400), style=wx.FRAME_FLOAT_ON_PARENT | wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU)
            self.Center()
            self.callback = None
            
            
            #Create menubar & statusbar
            self.master = master
            self.CreateStatusBar()
            self.SetStatusText("Connect Dialog")
            
            #Create toolbar
            self.panel = wx.Panel(self, -1)
            self.box = wx.BoxSizer(wx.VERTICAL)
            self.panel.SetSizer(self.box)
            self.panel.SetAutoLayout(True)
           


            self.toolbar = bp.ButtonPanel(self.panel, -1, "",
                                       agwStyle=bp.BP_USE_GRADIENT, alignment=bp.BP_ALIGN_LEFT)

            bpArt = self.toolbar.GetBPArt()
            bpArt.SetColour(bp.BP_BORDER_COLOUR, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_GRADIENT_COLOUR_FROM, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_GRADIENT_COLOUR_TO, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_BUTTONTEXT_COLOUR, wx.Colour(0, 0, 0))
            bpArt.SetColour(bp.BP_SEPARATOR_COLOUR,
                            bp.BrightenColour(wx.Colour(60, 11, 112), 0.85))
            bpArt.SetColour(bp.BP_SELECTION_BRUSH_COLOUR, wx.Colour(255, 255, 255))
            bpArt.SetColour(bp.BP_SELECTION_PEN_COLOUR, wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION))
            
            self.box.Add(self.toolbar, 0, wx.EXPAND)

            #tsize = (24,24)
            #new_bmp = wx.Image("image/Edit page.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
            '''            
            self.new_bmp =  wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR, tsize)
            self.edit_bmp = wx.ArtProvider.GetBitmap(wx.ART_EXECUTABLE_FILE, wx.ART_TOOLBAR, tsize)
            self.connect_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, tsize)
            self.disconnect_bmp = wx.ArtProvider.GetBitmap(wx.ART_MISSING_IMAGE, wx.ART_TOOLBAR, tsize)
            self.delete_bmp= wx.ArtProvider.GetBitmap(wx.ART_DELETE, wx.ART_TOOLBAR, tsize)
            self.quit_bmp= wx.ArtProvider.GetBitmap(wx.ART_QUIT, wx.ART_TOOLBAR, tsize)
            '''
            
            #self.toolbar.SetToolBitmapSize(tsize)

            #self.toolbar.AddLabelTool(10, "Connect", self.master.connect_bmp, shortHelp="Connect", longHelp="Long help for 'New'")
            btn = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.master.connect_bmp, text='  Connect  ',
                                shortHelp='Connect')
            self.toolbar.AddButton(btn)            
            self.Bind(wx.EVT_BUTTON, self.OnConnect, id=btn.GetId())

            
            #self.toolbar.AddLabelTool(60, "Disconnect", self.master.disconnect_bmp, shortHelp="Disconnect", longHelp="Long help for 'New'")
            #self.Bind(wx.EVT_TOOL, self.OnToolClick, id=60)
            
            #self.toolbar.AddLabelTool(20, "New", self.master.new_bmp, shortHelp="New Connection", longHelp="Long help for 'New'")
            btn = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.master.new_bmp, text='     New     ',
                                shortHelp='New Connection')
            self.toolbar.AddButton(btn)
            self.Bind(wx.EVT_BUTTON, self.OnNew, id=btn.GetId())

                        
            #self.toolbar.AddLabelTool(30, "Edit", self.master.edit_bmp, shortHelp="Edit Connection", longHelp="Long help for 'New'")
            btn = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.master.edit_bmp, text='      Edit     ',
                                shortHelp='Edit Connection')
            self.toolbar.AddButton(btn)
            self.Bind(wx.EVT_BUTTON, self.OnEdit, id=btn.GetId())

            
            #self.toolbar.AddLabelTool(40, "Delete", self.master.delete_bmp, shortHelp="Delete Connection", longHelp="Long help for 'New'")
            btn = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.master.delete_bmp, text='    Delete   ',
                                shortHelp='Delete Connection')
            self.toolbar.AddButton(btn)
            self.Bind(wx.EVT_BUTTON, self.OnDelete, id=btn.GetId())
            
            #self.toolbar.AddLabelTool(50, "Exit", self.master.quit_bmp, shortHelp="Exit", longHelp="Long help for 'New'")
            btn = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.master.quit_bmp, text='      Exit     ',
                                shortHelp='Exit')
            self.toolbar.AddButton(btn)
            self.Bind(wx.EVT_BUTTON, self.OnExit, id=btn.GetId())

            
            #self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolClick, id=10)
            #self.toolbar.Realize()
            self.toolbar.DoLayout()
            
            #Create listcontrol
            self.il = wx.ImageList(24, 24)
            self.image = wx.Bitmap("image/connect_icon.png", wx.BITMAP_TYPE_PNG)
            self.idx1 = self.il.Add(self.image)

            self.listctrl = wx.ListCtrl(self.panel, -1, style=wx.LC_REPORT | wx.LC_NO_HEADER, size=(300, -1))
            self.listctrl.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
            self.listctrl.InsertColumn(0, "List", width=300)
            #self.listctrl.InsertColumn(1, "List",wx.LIST_FORMAT_CENTER, width = 300)
            self.listctrl.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL,
                                        False, 'Verdana'))
            self.box.Add(self.listctrl, 1, wx.EXPAND | wx.ALL, 50)
            self.LoadDataListCtrl()
            self.Bind(wx.EVT_CLOSE, self.OnExit)

            self.listctrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.SelectedItem)
            self.listctrl.Bind(wx.EVT_LEFT_DCLICK, self.OnConnect)
            # setting
            icon = wx.Icon("image/house_16.ico", wx.BITMAP_TYPE_ICO, 16, 16)
            self.SetIcon(icon)
            self.listctrl.getima
        except Exception, e:
            ######print type(e)
            ######print e
            return

    
    
    def SelectedItem(self, event):
        self.master.currentItem = event.m_itemIndex
        self.master.namecn, self.master.hostnamecn, self.master.usernamecn, self.master.pwcn = self.master.listconnections[self.master.currentItem]

        event.Skip()
    
    def getColumnText(self, index, col):
        item = self.listctrl.GetItem(index, col)
        return item.GetText()


    def LoadDataListCtrl(self):
        
        self.listctrl.DeleteAllItems()
        self.master.LoadDataConnection()

        #######print self.listconnections
        for i in range(len(self.master.listconnections)):
            self.listctrl.InsertImageStringItem(sys.maxint, self.master.listconnections[i][0], 0)

        self.listctrl.SetColumnWidth(0, wx.LIST_AUTOSIZE)
        #self.listctrl.SetColumnWidth(1, wx.LIST_AUTOSIZE)
       
    def OnConnect(self, event):
        if self.master.currentItem < 0:
            wx.MessageBox("Please choose a connection")
            return
        self.ProcessOpen()
        
    def ProcessOpen(self, event=None):
        self.master.UpdateStatusBar4()
        self.master.UpdateStatusBar3()
        self.master.UpdateStatusBar5()
        self.master.UpdateStatusBar6()
        try:
            
            if self.master.currentItem >= 0:

                ######print 'start'
                currentItem = self.listctrl.GetItemText(self.master.currentItem)
                ######print currentItem            
                for nameobj in self.master.listconnections:
                    if currentItem == nameobj[0]:
                        ######print 'e'         l;;;;               
                        self.master.namecn = nameobj[0]
                        self.master.hostnamecn = nameobj[1]
                        self.master.port = 22
                        self.master.usernamecn = nameobj[2]
                        self.master.pwcn = nameobj[3]
                        break

                self.master.client = paramiko.SSHClient()
                self.master.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                self.master.client.load_system_host_keys()
                self.master.client.connect(self.master.hostnamecn, port=22, username=self.master.usernamecn, password=self.master.pwcn)
                #self.client._transport.sock.settimeout(100)
                self.master.client.set_log_channel("logchanel.txt")
                self.master.channel = self.master.client._transport.open_session()
                #self.channel.settimeout(100)
                self.term = 'vt100'
                #if self.master.co==1:
                #####print self.master.colpaper, self.master.rowpaper
                #####print 'ddd'
                self.master.channel.get_pty(self.term, width=112, height=40) 
                    
                self.master.channel.invoke_shell()
                self.master.connected = True
                self.master.co = 1
                time.sleep(0.1)
                self.master.accept_host = ''
#                ######print 'begin'
#                ######print self.master.accept_login
                #self.text.connected == True
                '''dlg = wx.MessageDialog(self,"Connect successful !", 'Notification', wx.OK | wx.ICON_INFORMATION)
                dlg.ShowModal()
                dlg.Destroy()'''
                
                self.master.isconnect = True
                self.master.isresize = True
                self.master.UpdateStatusControl()
       
#                ######print 'dialog'
                #self.accept_host_log = self.accept_host
                #self.text.mark_set('insert','end-1line lineend')
                
#                ######print 'dialog'
#                ######print len(self.master.accept_host)
#                ######print '.'+self.master.accept_host+'.'
                self.master.text.SetFont(self.master.fontn)
                self.master.VIlevel = 2
                self.master.top_data = COMMAND1(self.master)
                self.master.top_data.start()
                self.master.dynamis_name = 'COMMAND'
            
#                ######print 'dialog'
#                ######print '.'+self.master.text.GetString(76,78)+'.'
#                ######print self.master.text.GetNumberOfLines()
#                ######print self.master.text.GetLastPosition()
#                ######print 'dialog'
#                begin = self.master.text.GetLineLength( self.master.text.GetNumberOfLines())
#                points = self.master.text.GetFont().GetPointSize()  # get the current size
#                ######print points
#                #f = wx.Font(points+3, wx.NORMAL, wx.NORMAL, wx.BOLD, True)   
#                ######print begin
                #######print self.master.text.GetLastPosition()
                #self.master.text.SetStyle(0 ,self.master.text.GetLastPosition(), wx.TextAttr('BLACK',wx.NullColour, self.master.fontb))
               
#                ######print 'a'
#                ######print '.'+self.master.text.GetRange(0, 80)+'.'
#                ######print self.master.text.GetInsertionPoint()
#                #self.master.text.SetInsertionPointEnd()
#                ######print self.master.text.GetInsertionPoint()
                self.master.indexText = self.master.text.GetLastPosition()

                #self.master.sftp_host = self.master.channel.get_transport().open_sftp_client()
                                
#                ######print 'end'
                self.Destroy()
                if self.callback <> None:
                    self.callback()
                self.master.text.SetFocus()
                '''self.disable_text = self.text.get(1.0, Tkinter.END)
                self.contents = self.text.get(1.0, Tkinter.END)                
                self.text.tag_add("bold", "%s-%dc" % (Tkinter.INSERT, len(self.accept_host_log)), Tkinter.INSERT)
                
                for line in self.accept_host.split('\n'):
                    self.locate= line
                #self.locate = self.locate.strip()
                self.text.mark_set('insert','end-1line lineend')
                self.text.focus_set()
                self.text.yview('end')
                self.toggle()

                stdin, stdout, stderr = self.client.exec_command("pwd")
                 
                self.connect_folder = str(stdout.read().strip())
                self.current_folder = self.connect_folder
                self.text.connected = True'''
                try:
                    write = WriteLogDB("login", self.master.hostnamecn, self.master.usernamecn, self.master.pwcn, False)
                    write.start()
                except Exception, e:
                    print e
              
            else:
                wx.MessageDialog(self, "Please choose a connection", "Error Open", wx.OK | wx.ICON_WARNING)
                self.Destroy()
                #self.OnOpenConnect()
        except:
            wx.MessageBox("Cannot connect to host", "Error Client", wx.OK)
            #statusbar
            self.master.statusbar.SetStatusText("", 1)
            self.master.statusbar.SetStatusText("", 2)
            self.master.statusbar.SetStatusText("", 3)
            self.master.statusbar.SetStatusText("", 4)
            self.master.statusbar.SetStatusText("", 5)
            self.master.statusbar.SetStatusText("", 6)
            return
            #self.OnOpenConnect()

        #save the index last for the text
        #self.indexText = self.text.index(Tkinter.INSERT)
        #self.text.focus()
    
        
        
    def OnDelete(self, event):
        if self.master.currentItem < 0:
            wx.MessageBox("Please choose a connection")
            return
        dlg = wx.MessageDialog(self, "Do you want to delete ?", "Notification", wx.YES_NO | wx.ICON_QUESTION)
        if dlg.ShowModal() == wx.ID_YES:
            self.master.listconnections.remove([self.master.namecn, self.master.hostnamecn, self.master.usernamecn, self.master.pwcn])        
            if len(self.master.listconnections) != 0:
                self.master.WriteFileConnection(True)
            else:
                os.remove(self.master.fileopen)
            self.LoadDataListCtrl()
        else:
            dlg.Close()
        
    def OnExit(self, event):
        self.Destroy()
        self.result = event.EventObject.GetId()
        if self.callback <> None:
                self.callback()
                return


            
    def OpenNewOrEditDlg(self, tp):
        self.Enable(False)
        connectDlg = NewOrEditDlg(self, tp)
        connectDlg.callback = self.x.next
        connectDlg.CenterOnParent()
        connectDlg.Show()
      
        connectDlg.Raise()
        yield None
        self.Enable(True)
        yield None


        
    def OnNew(self, event):
        self.x = self.OpenNewOrEditDlg(0)
        self.x.next()
        
    def OnEdit(self, event):
        
        if self.master.currentItem < 0:
            wx.MessageBox("Please choose a connection")
            return
        self.x = self.OpenNewOrEditDlg(1)
        self.x.next()


         


                
class COMMAND1(threading.Thread):
    def __init__(self, ssh, mode=None):
        self.lock = False
        self.processing = True
        self.currentPosition = None
        threading.Thread.__init__(self) 
        self.ssh = ssh
        self.ssh.processing = True
    
    def drop(self):
        if self.currentPosition != None:
            self.ssh.downPoint, self.ssh.upPoint = self.ssh.text.GetSelection()
            self.ssh.text.Freeze()
            currentScroll = self.ssh.text.GetScrollPos(wx.VERTICAL)
            self.ssh.text.SetStyle(self.ssh.downPoint, self.ssh.upPoint, (wx.TextAttr(wx.NullColor, '#3399ff')))
            self.ssh.text.SetInsertionPoint(self.currentPosition)
            while currentScroll < self.ssh.text.GetScrollPos(wx.VERTICAL):
                    #print '<',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
                self.ssh.text.ScrollLines(-1)
                  
            while currentScroll > self.ssh.text.GetScrollPos(wx.VERTICAL):
                #print '>',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
                self.ssh.text.ScrollLines(1)
                if currentScroll == self.ssh.text.GetScrollPos(wx.VERTICAL) + 1:
                    break
                
            self.ssh.text.Thaw()
            self.lock = False
            self.currentPosition = None
            

    
    def drag(self): 
        if self.currentPosition != None:
            time.sleep(0.3)
            
        self.currentPosition = self.ssh.text.GetInsertionPoint()
        while True:
            if self.processing == False:
                self.lock = True
                self.ssh.text.Thaw() 
                return
               
        return    
      
    def run(self):
        try:
            self.ssh.processing = True
            try:
                self.ssh.numend = self.ssh.rowpaper
                self.ssh.numstart = 1
            except Exception, e:
                pass
                #####print type(e)
                #####print e   
            time.sleep(0.1)
#           self.ssh.text.SetStyle(0, self.ssh.text.GetLastPosition(), wx.HSCROLL)
            self.ssh.text.SetScrollPos(wx.VERTICAL, self.ssh.text.GetScrollRange(wx.VERTICAL))
            self.ssh.text.Refresh()
            self.ssh.codeteamp = ''
            finished = False
            self.ssh.processing = False
#            self.ssh.text.SetInsertionPoint(self.ssh.text.XYToPosition(0, self.ssh.text.GetNumberOfLines()))
                #self.deleteRestOfLine(line)
            #clearScreen = int(self.ssh.rowpaper)*'\r\n'
            #self.ssh.text.AppendText(clearScreen)
            commandLine = ''
            currentCommand = ''
            currentContent = ''
            while True:     
                if self.lock == True:
                    time.sleep(0.05)
                    continue
                self.ssh.accept_host = self.ssh.channel.recv(1024).replace("\r\r", "\r")
                if self.lock == True:
                    self.ssh.accept_host = self.ssh.accept_host.decode(wx.GetDefaultPyEncoding(), 'ignore')
                    self.ssh.codeteamp = self.ssh.accept_host
                    continue
               
                self.processing = True
                self.ssh.accept_host = self.ssh.accept_host.decode(wx.GetDefaultPyEncoding(), 'ignore')
                #print 'data ve truoc + codeteamp', self.ssh.accept_host.__len__()
                self.ssh.accept_host = self.ssh.codeteamp + self.ssh.accept_host
                #print 'data ve sau + codeteamp', self.ssh.accept_host.__len__()
                if self.ssh.accept_host == '' and self.ssh.channel.exit_status_ready():
                    #print 'data'
                    write = WriteLogDB('logout', self.ssh.hostnamecn, self.ssh.usernamecn, self.ssh.pwcn, False)
                    write.start()
                    self.ssh.Disconnect()
                    break
                if self.ssh.accept_host[-1:] == '\r':
                    self.ssh.codeteamp = '\r'
                    self.ssh.accept_host = self.ssh.accept_host[:-1]
                else:
                    self.ssh.codeteamp = ''
                self.length = self.ssh.accept_host.__len__() 
                if self.ssh.text.GetLastPosition() + self.length > 60000:
                    #print 'data ve truoc khi vao ham dang test', self.length
                    #print 'update1',self.ssh.text.GetLastPosition()
                    linedel = self.ssh.text.GetNumberOfLines() / 2
                    #print 'frow', self.ssh.frow
                    if linedel < self.ssh.frow:
                        #print 'linedel < self.ssh.frow'
                        self.ssh.updatePosition(self.ssh.text.GetLastPosition() + self.length, linedel)
                    else:
                        #print 'linedel >= self.ssh.frow'
                        linedel = self.ssh.text.GetNumberOfLines() / 3
                        self.ssh.updatePosition(self.ssh.text.GetLastPosition() + self.length, linedel)
                    #print 'update2',self.ssh.text.GetLastPosition()
                    
                currentContent += self.ssh.accept_host
               ##print 'data nhan duoc',self.ssh.accept_host
                if re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\]. .*\n', currentContent) != None: 
                    
                    if self.ssh.runScript == True and re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\]. \.\/EliTech_Script', currentContent, re.DOTALL) != None:
                       ##print 'false',self.ssh.accept_host
                        #print 'subsub'
                        self.ssh.accept_host = re.sub(r'^.*EliTech_Script|^.*\n|^.*', '\n', self.ssh.accept_host)
                        self.ssh.text.Enable(True)    
                        self.ssh.runScript = False
                        currentContent = ''
                        self.ssh.sftp.remove('EliTech_Script')
                    x, y = self.ssh.text.PositionToXY(self.ssh.text.GetInsertionPoint())
                    temp = self.ssh.text.GetLineText(y)
                    if re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\]. \n', currentContent):
                        currentContent = ''
                        currentCommand = ''
                    elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+tree\n|\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+tree .*\n', currentContent):
                        currentContent = ''
                        currentCommand = 'TREE'
                        
                    elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+tree\n|\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+tree .*\n', currentContent):
                        currentContent = ''
                        currentCommand = 'TREE'
                         
                    elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+top|\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+top .*\n', currentContent):
                        currentContent = ''
                        currentCommand = 'TOP'
                        
                    elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+vi|\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+vi .*\n', currentContent):
                        currentContent = ''
                        currentCommand = 'VI'
                    
                    elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+tree\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+tree .*', temp):
                        currentContent = ''
                        currentCommand = 'TREE'
                        
                    elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+tree|\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+tree .*', temp):
                        currentContent = ''
                        currentCommand = 'TREE'
                         
                    elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+top|\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+top .*', temp):
                        currentContent = ''
                        currentCommand = 'TOP'
                        
                    elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+vi|\[[^\[]+\@[^\[]+ [^\[]+\].[ ]+vi .*', temp):
                        currentContent = ''
                        currentCommand = 'VI'
                                            
                    else:
                        currentContent = currentContent[-200:]
                        currentCommand = ''
                elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\]. ', currentContent) != None: 
                    if re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\]. ', currentContent):
#                        currentContent = ''
                        currentCommand = ''                    
                        
                currentContent = currentContent[-200:]
                
                if currentCommand == 'TREE': 
                    self.ssh.text.write(self.ssh.accept_host)
                    time.sleep(0.01)
                    
                elif currentCommand == 'TOP':
                    if self.ssh.downPoint != -1 and  self.ssh.upPoint != -1:
#                        print 'top',self.ssh.downPoint,self.ssh.upPoint,self.ssh.text.GetInsertionPoint()
                        self.ssh.text.Freeze()
                        currentScroll = self.ssh.text.GetScrollPos(wx.VERTICAL)
                        self.ssh.text.SetStyle(self.ssh.downPoint, self.ssh.upPoint, (wx.TextAttr(wx.NullColor, 'WHITE')))
                        while currentScroll < self.ssh.text.GetScrollPos(wx.VERTICAL):
                                #print '<',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
                            self.ssh.text.ScrollLines(-1)
                              
                        while currentScroll > self.ssh.text.GetScrollPos(wx.VERTICAL):
                            #print '>',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
                            self.ssh.text.ScrollLines(1)
                            if currentScroll == self.ssh.text.GetScrollPos(wx.VERTICAL) + 1:
                                break
                        self.ssh.text.Thaw()
                    
                    if (self.ssh.frow < self.ssh.downPoint or self.ssh.frow < self.ssh.upPoint) and (self.ssh.text.GetInsertionPoint() < self.ssh.downPoint or self.ssh.text.GetInsertionPoint() < self.ssh.upPoint):
                        self.ssh.downPoint = -1
                        self.ssh.upPoint = -1
                        
                    self.ssh.text.Freeze()        
                    self.ssh.ConvertCode(self.ssh.accept_host)
                    self.ssh.text.Thaw()
                    
                elif currentCommand == 'VI':                   
                    self.ssh.text.Freeze()        
                    self.ssh.ConvertCode(self.ssh.accept_host)
                    self.ssh.text.Thaw()
                    
                elif self.ssh.runScript:
                    pass
                else:   
#                    print 'currentContent',self.ssh.accept_host
                    self.ssh.ConvertCode(self.ssh.accept_host)
                    time.sleep(0.005)
                self.ssh.UpdateStatusBar2()                   
                if self.ssh.waiting == True:       
                    commandLine += self.ssh.accept_host
                    temppwd = re.search(r'pwd.*\[[^\[]+\@[^\[]+ [^\[]+\].*', commandLine, re.DOTALL)
                    if temppwd != None:
                        temppwd = temppwd.group()
                        temppwd = temppwd[temppwd.find('\r\n') + 2:]
                        temppwd = temppwd[:temppwd.find('\r\n')]
                        self.ssh.uploadFile(temppwd)                     
                        self.ssh.waiting = False                        
                        commandLine = ''
#                       ./' + EliTech_Script + '\n'
                if self.ssh.runScript == True:
                    commandLine += self.ssh.accept_host
                    temppwd = re.search(r'pwd.*\[[^\[]+\@[^\[]+ [^\[]+\].*', commandLine, re.DOTALL)
                    if temppwd != None:
                        temppwd = temppwd.group()
                        temppwd = temppwd[temppwd.find('\r\n') + 2:]
                        temppwd = temppwd[:temppwd.find('\r\n')]
                        self.ssh.uploadScript(temppwd)                     
#                        self.ssh.runScript = False                        
                        commandLine = ''
                 
                self.processing = False
        except Exception , prt:
            print 'loi 2', prt
#            self.ssh.Disconnect()
#            dlg = wx.MessageDialog(self.ssh,"Please, reconnect .", 'Notification', wx.YES_NO | wx.ICON_QUESTION)
#            if dlg.ShowModal() == wx.ID_YES:
#                ###print 'a'
#                dlg.Destroy()
#                self.ssh.OnReconnect()
#                ##print ' b'
            pass

        finally:
            #print 'final top'
            self.ssh.processing = False
            if finished == True:
                try:
                    self.ssh.indexText = self.ssh.text.GetLastPosition()
                    self.ssh.top_data = None
                    self.ssh.dynamis_name = ''
                except:
                    pass
                    #####print 'da vao day'            




class FileDrop(wx.FileDropTarget):
    def __init__(self, master, window):
        wx.FileDropTarget.__init__(self)
        self.window = window
        self.master = master

    def OnDropFiles(self, x, y, filenames):
        self.master.filepath = []
        for name in filenames:
            try:
                self.master.filepath.append(name)
            except Exception, e:
                wx.MessageBox('Cannot send this file !', 'Error !', wx.OK)
        self.master.ProcessSendFile()
        
class WriteLogDB(threading.Thread):
    def __init__(self, status, hostnamecn, username, password, flag, mode=None):
        self.status = status
        self.hostnamecn = hostnamecn
        self.usernamecn = username 
        self.pwcn = password
        self.flag = flag
        threading.Thread.__init__(self) 
        pass
    
    def getExternalIP(self):
        f = urllib.urlopen("http://www.canyouseeme.org/")
        html_doc = f.read()
        f.close()
        m = re.search('(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', html_doc)
        return m.group(0)
    
   
    def getDateTimeSV(self):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.hostnamecn, port=22, username=self.usernamecn, password=self.pwcn)
        command1 = 'date +"%Y-%m-%d %T"'
        stdin, stdout, stderr = ssh.exec_command(command1)
        dateresult = stdout.read().splitlines()
        return dateresult[0]
        
    def WriteLogFile(self, status):
       
        pass
    
    def run(self):
        myip = self.getExternalIP()
        local_time = time.strftime('%Y-%m-%d %H:%M:%S')
        ins_time = self.getDateTimeSV()
        conn = MySQLdb.connect(host="1.234.20.151",
                  user="cam",
                  passwd="5678",
                  db="eliremote")
        x = conn.cursor()
        x.execute ("INSERT INTO log_ssh (local_ip,local_time,version,status,ins_time) VALUES (%s,%s,%s,%s,%s) ", (myip, local_time, 'pc', self.status, ins_time))
        x.close()
        conn.close()
        
        if self.flag:
            pythoncom.CoInitialize()
            id = GetCurrentProcessId()
            print id
            WMI = GetObject('winmgmts:')
            processes = WMI.InstancesOf('Win32_Process')
            for proc in processes:
                if proc.Properties_("ProcessID").Value == id:
                    proc.Terminate
            pythoncom.CoUninitialize()
        return
        
class SSH(threading.Thread, wx.Frame):
    def __init__(self, shadesubmenus=False):
        try:
            wx.Frame.__init__(self, None, -1, 'Elisoft CRT', size=(900, 700))
            self.SetMinSize((650, 500))
#            self.myip = self.getExternalIP()
            ##########################################
#            try:
#                SettingWinSecurity(self.GetHandle())
#            except Exception,e:
#                pass
            ###########################################
            self.bShadeSubMenus = shadesubmenus
            self.size = self.GetSize()
            self.hwnd = self.GetHandle()
            self.Center()
            self.charset = 'euc-kr'
            self.save_insert = 0
            self.sendfile = 0
            self.rowpaper = 40
            self.colpaper = 112
            #self.LoadFont() 
            #---event-- drag-copy-----
            self.downPoint = -1  
            self.upPoint = -1 
            self.previousPoint = -1
            self.trend = 1
            self.trendFlag = False
            self.pwd = None
            self.textValue = ''

            #version = self.readVersion('update_version.ini')
            self.SetTitle('Elisoft CRT ' + self.readVersion('update_version.ini'))
            
            #Xu ly icon
            #tsize = (24,24)
            self.nBytes = 0;
            self.new_bmp = wx.Bitmap("image/new.png", wx.BITMAP_TYPE_PNG)
            self.edit_bmp = wx.Bitmap("image/edit.png", wx.BITMAP_TYPE_PNG)
            self.connect_bmp = wx.Bitmap("image/connect.png", wx.BITMAP_TYPE_PNG)
            self.disconnect_bmp = wx.Bitmap("image/disconnect.png", wx.BITMAP_TYPE_PNG)
            self.delete_bmp = wx.Bitmap("image/Delete.png", wx.BITMAP_TYPE_PNG)
            self.quit_bmp = wx.Bitmap("image/quit.png", wx.BITMAP_TYPE_PNG)
            self.update_bmp = wx.Bitmap("image/update.png", wx.BITMAP_TYPE_PNG)
            self.sendfile_bmp = wx.Bitmap("image/send_file.png", wx.BITMAP_TYPE_PNG)
            self.setting_bmp = wx.Bitmap("image/setting.png", wx.BITMAP_TYPE_PNG)
            self.notepad_bmp = wx.Bitmap("image/notepad.png", wx.BITMAP_TYPE_PNG)
            
            #Create menuitem
            self.menuFile = wx.Menu()
            item = wx.MenuItem(self.menuFile, 1, "Connect")
            item.SetBitmap(self.connect_bmp)
            self.menuFile.AppendItem(item)

            item = wx.MenuItem(self.menuFile, 2, "Disconnect")
            item.SetBitmap(self.delete_bmp)
            self.menuFile.AppendItem(item)
            
            
            
            self.menuFile.AppendSeparator()
            
            item = wx.MenuItem(self.menuFile, 3, "Exit")
            item.SetBitmap(self.quit_bmp)
            self.menuFile.AppendItem(item)
            
            self.menuOption = wx.Menu()
            item = wx.MenuItem(self.menuOption, 6, "Setting")
            item.SetBitmap(self.setting_bmp)
            self.menuOption.AppendItem(item)

            self.menuProcess = wx.Menu()
            item = wx.MenuItem(self.menuProcess, 4, "Send File")
            item.SetBitmap(self.sendfile_bmp)
            self.menuProcess.AppendItem(item)

            self.menuScript = wx.Menu()
            item = wx.MenuItem(self.menuScript, 5, "Run Script")
            item.SetBitmap(self.update_bmp)
            self.menuScript.AppendItem(item)
            
            icon = wx.Icon("image/house_16.ico", wx.BITMAP_TYPE_ICO, 16, 16)
            self.SetIcon(icon)
            
            
            item = self.menuFile.FindItemById(2)
            item.Enable(False)
            
            #Create menubar & statusbar
            self.menuBar = wx.MenuBar()
            self.menuBar.Append(self.menuFile, "File")
            #self.menuBar.Append(self.menuOption, "Options")
            self.menuBar.Append(self.menuProcess, "Process")
            self.menuBar.Append(self.menuScript, "Script")
            
            self.SetMenuBar(self.menuBar)
            
            self.statusbar = self.CreateStatusBar()
            self.statusbar.SetFieldsCount(7)
            self.SetStatusWidths([-1, 50, 50, 100, 50, 30, 60])
            self.statusbar.sizeChanged = False
            #self.statusbar.Bind(wx.EVT_SIZE, self.OnSize)
            self.statusbar.Bind(wx.EVT_IDLE, self.OnIdle)
            
            
            self.statusbar.SetStatusText("A Custom StatusBar...", 0)
            self.statusbar.SetStatusText("", 1)
            self.statusbar.SetStatusText("", 2)
            self.statusbar.SetStatusText("", 3)
            self.statusbar.SetStatusText("", 4)
            self.statusbar.SetStatusText("", 5)
            self.statusbar.SetStatusText("", 6)

            

            #Action menuitem
            self.Bind(wx.EVT_MENU, self.OnConnect, id=1)
            self.Bind(wx.EVT_MENU, self.OnDisconnect, id=2)
            self.Bind(wx.EVT_MENU, self.OnExit, id=3)
            self.Bind(wx.EVT_MENU, self.OnSendFile, id=4)
            self.Bind(wx.EVT_MENU, self.OnRunScript, id=5)
            #self.Bind(wx.EVT_MENU, self.OnSetting, id=6)
            
            self.Bind(wx.EVT_FIND, self.OnFindAct)
            self.Bind(wx.EVT_FIND_NEXT, self.OnFindAct)
            self.Bind(wx.EVT_FIND_REPLACE, self.OnFindAct)
            self.Bind(wx.EVT_FIND_REPLACE_ALL, self.OnFindAct)
            self.Bind(wx.EVT_FIND_CLOSE, self.OnFindClose)
            self.Bind(wx.EVT_CLOSE, self.OnClose)
            #Create toolbar
            self.panel = wx.Panel(self, -1)
            self.box = wx.BoxSizer(wx.VERTICAL)
            #self.box = wx.BoxSizer(wx.HORIZONTAL)
            self.panel.SetSizer(self.box)
            self.panel.SetAutoLayout(True)
            
            self.top_data = None

            self.toolbar = bp.ButtonPanel(self.panel, -1, "",
                                          agwStyle=bp.BP_USE_GRADIENT, alignment=bp.BP_ALIGN_LEFT)
            
            self.box.Add(self.toolbar, 0, wx.EXPAND)
            
            bpArt = self.toolbar.GetBPArt()
            bpArt.SetColour(bp.BP_BORDER_COLOUR, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_GRADIENT_COLOUR_FROM, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_GRADIENT_COLOUR_TO, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_BUTTONTEXT_COLOUR, wx.Colour(0, 0, 0))
            bpArt.SetColour(bp.BP_SEPARATOR_COLOUR,
                            bp.BrightenColour(wx.Colour(60, 11, 112), 0.85))
            bpArt.SetColour(bp.BP_SELECTION_BRUSH_COLOUR, wx.Colour(255, 255, 255))
            bpArt.SetColour(bp.BP_SELECTION_PEN_COLOUR, wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION))
           

            
            self.btnconnect = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.connect_bmp, text='  Connect  ',
                                shortHelp='Connect')
            self.toolbar.AddButton(self.btnconnect)
            self.Bind(wx.EVT_BUTTON, self.OnConnect, id=self.btnconnect.GetId())

            self.btndisconnect = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.delete_bmp, text='Disconnect',
                                shortHelp='Disconnect')
            self.toolbar.AddButton(self.btndisconnect)
            self.Bind(wx.EVT_BUTTON, self.OnDisconnect, id=self.btndisconnect.GetId())
            self.btndisconnect.Enable(False)
            self.toolbar.AddSeparator()
            
            self.btnsend = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.sendfile_bmp, text='      Send     ',
                                shortHelp='Send')
            self.toolbar.AddButton(self.btnsend)
            ###########################################
            self.Bind(wx.EVT_BUTTON, self.OnSendFile, id=self.btnsend.GetId())
            self.btnsend.Enable(False)
            
            #########################MinhTuan-SendFileNew
            self.btnsendNew = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.sendfile_bmp,text='      Send     ',
                                shortHelp='Send')
            self.toolbar.AddButton(self.btnsendNew)
            ###########################################
            self.Bind(wx.EVT_BUTTON, self.OnSendFileNew, id=self.btnsendNew.GetId())            
            ########################
            
            self.toolbar.AddSeparator()
            
            self.btnNotepad = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.notepad_bmp, text='Notepad',
                                shortHelp='Notepad')
            self.toolbar.AddButton(self.btnNotepad)
            self.Bind(wx.EVT_BUTTON, self.OnNotePad, id=self.btnNotepad.GetId())
            self.btnNotepad.Enable(False)
            self.toolbar.AddSeparator()
        
            self.btnSetting = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.notepad_bmp, text='Setting',
                                shortHelp='Setting')
            self.toolbar.AddButton(self.btnSetting)
            self.Bind(wx.EVT_BUTTON, self.OnSetting, id=self.btnSetting.GetId())
#            self.btnSetting.Enable(False)
            self.toolbar.AddSeparator()
      
            btn = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.quit_bmp, text='      Exit     ',
                                shortHelp='Exit')
            self.toolbar.AddButton(btn)
            ###########################################
            self.Bind(wx.EVT_BUTTON, self.OnExit, id=btn.GetId())
             
#            btn = bp.ButtonInfo(self.toolbar, wx.NewId(),
#                                self.quit_bmp,text='      Stop     ',
#                                shortHelp='Stop')
#            self.toolbar.AddButton(btn)
#            self.Bind(wx.EVT_BUTTON, self.OnStop, id=btn.GetId())   
            #  Courier New or Lucida Console and Monaco

            ######################################################
            self.toolbar.DoLayout()


            self.fontn = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, face="INCONSOLATA", encoding=wx.FONTENCODING_DEFAULT)
            self.fontb = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, face="INCONSOLATA" , encoding=wx.FONTENCODING_DEFAULT)


            
            #Create textcontrol
            #font = wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
            #self.panel.SetFont(font)
            ######print "platform :" + sys.platform
            if sys.platform == "win32":                                                                                                                                                                                                               

                self.fontn = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, face="INCONSOLATA", encoding=wx.FONTENCODING_DEFAULT)



            '''elif sys.platform == "darwin":
                font = wx.Font(11, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, 
                                                           wx.FONTWEIGHT_NORMAL,
                                                           face="Monaco")'''
            self.panel.SetFont(self.fontn)
            self.list_of_paintables = []
  
            self.text = wx.TextCtrl(self.panel, -1, "Text Control\n", style=wx.TE_MULTILINE | wx.TE_RICH2)#|wx.HSCROLL)
            #self.text.SetBackgroundColour("#fffff")
            self.text.SetDropTarget(wx.PyDropTarget())
            
            self.text.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)
            self.text.SetFont(self.fontn)
            points = self.text.GetFont().GetPointSize() 
            self.backgroundB = wx.Font(points + 3, wx.ROMAN, wx.FONTWEIGHT_NORMAL, wx.BOLD, True)
            #self.size = 512*wx.TE_RICH
            self.text.SetFocus()
            self.text.Bind(wx.EVT_MOUSE_CAPTURE_CHANGED, self.mouse, self.text)
            self.text.Bind(wx.EVT_SCROLLBAR, self.mouse)
#            self.text.Bind(wx.EVT_WINDOW_CREATE,self.pow)
            
            
            self.text.Bind(wx.EVT_MOUSE_EVENTS, self.mouser_event, self.text)
            self.text.Bind(wx.EVT_LEFT_DCLICK, self.mouse, self.text)
#            self.text.Bind(wx.EVT_LEFT_DOWN,self.mouser_down,self.text)
#            self.text.Bind(wx.EVT_LEFT_UP,self.mouser_up,self.text)
#            self.text.Bind(wx.EVT_mo,self.lelfdown)
#            self.text.Bind(wx.EVT_MOTION,self.OnDragInit)
            self.text.Bind(wx.EVT_LEFT_DOWN, self.leftdown)
            self.text.Bind(wx.EVT_LEFT_UP, self.leftup)
            self.text.Bind(wx.EVT_CHAR, self.key, self.text)
            self.text.Bind(wx.EVT_KEY_DOWN, self.onBack, self.text)
#            self.text.Bind(wx.EVT_SCROLL, self.OnScroll, self.text)
#            self.text.Bind(wx.EVT_SCROLLWIN, self.OnScroll, self.text)
#            self.text.Bind(wx.EVT_SCROLL_CHANGED, self.OnScroll, self.text)
#            self.text.Bind(wx.EVT_s, self.OnScroll, self.text)
#            self.text.Bind(wx.EVT_ACTIVATET, self.onFocuss, self.text)
#            self.text.Bind(wx.EVT_SET_CURSOR, self.onFocuss, self.text)
            #self.text.Bind()
            self.text.SetInsertionPoint(0)
            self.text.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
            
            
#            self.panel.Bind(wx.EVT_SET_FOCUS, self.OnFocus)
#            self.panel.Bind(wx.EVT_KILL_FOCUS, self.OnKFocus)
#            self.panel.Bind(wx.EVT_SCROLLWIN, self.OnScroll)
            #self.text.get
            self.box.Add(self.text, 1, wx.EXPAND)
            
            
            self.insert_temp = self.text.GetLastPosition()
            
            self.indexText = self.text.GetLastPosition()
            
            wx.CallAfter(self.text.SetInsertionPoint, self.indexText)
            
            
            #self.ChangeMenuBarColor()
            self.isconnect = False
            self.heigth = 40
            self.UpdateStatusControl()
            self.settingForBeginning()
            self.text.Bind(wx.EVT_SIZE, self.OnSize)

            dt = FileDrop(self, self.text)
            self.text.SetDropTarget(dt)
            
        except Exception, e:
            ######print type(e)
           ##print e
            return
        
    def readVersion(self, pathFile):
        file = ConfigParser.RawConfigParser(allow_no_value=True)
        try:
            file.read(pathFile)
        except Exception, e:
            return ''
        arrRoot = file.sections()
        if len(arrRoot) > 0:
            for nodeRoot in arrRoot:
                if nodeRoot == 'SSHClient_WX.exe':
                    arrKeys = file.options(nodeRoot)
                    if len(arrKeys) > 0:
                        return file.get(nodeRoot, 'date')[:8]
        return ''
    
#    def OnFocus(self,event):
#       ##print 'vao focus'
#        event.Skip()
#        pass
#    
#    def OnKFocus(self,event):
#       ##print 'vao Kfocus'
#        event.Skip()
#        pass
#    
#    def OnScroll(self,event):
#       ##print 'vao scoll'
#        event.Skip()
#        pass
    
    def OnRunScript(self, event):
        time.sleep(0.5)
        try:
           ##print 'Vao day 1'
            if not self.isconnect:
                wx.MessageBox("Required connect to server", "Notice", wx.OK)
                return
            elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].*', self.text.GetLineText(self.text.GetNumberOfLines() - 1), re.DOTALL) == None:
                wx.MessageBox("Stop your current process.", "Notice", wx.OK | wx.ICON_INFORMATION)
                return
            dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", "All files (*.*)|*.*", wx.OPEN)
            if dialog.ShowModal() == wx.ID_OK:
                self.filepath = []
                self.filepath.append(dialog.GetPath())
                self.runScript = True
                self.text.Enable(False)
                self.text.AppendText('Starting Script...')
                
            else:
                return
            dialog.Destroy()
        except Exception, e:
            self.text.Enable(True)
           ##print e
            pass
        
        if(len(self.filepath) != 0):
           ##print 'Vao day 2.1'
            try:
                #paramiko.util.log_to_file('log.txt')
                try:
                    lastLine = self.text.GetLineText(self.text.GetNumberOfLines() - 1)
                    if re.search(r'--more--', lastLine) != None:
                        self.channel.send("q")
                    elif re.search(r'possibilities\? \(y or n\)', lastLine) != None:
                        self.channel.send("n")
                    else:    
                        self.channel.send(chr(27) + chr(26))
                    self.channel.send("\npwd\n")

                except Exception, e:
                   ##print e
                    wx.MessageBox("Can't run this script", "Error", wx.OK)
                    self.channel.send('\n')
                    self.text.Enable(True)
                    self.runScript = False
                    self.filepath = ''
                    pass
                self.indexText = self.text.GetLastPosition()
     
            except Exception, e:
                wx.MessageBox("Can't run this script", "Error", wx.OK)
                self.channel.send('\n')
                self.indexText = self.text.GetLastPosition()
                self.filepath = ''
                self.runScript = False
                self.text.Enable(True)
                ######print type(e)
                ######print e
                return
        
            
    def uploadScript(self, pwd):
       ##print 'pwd',pwd
        try:
            self.sftp = self.channel.get_transport().open_sftp_client()
            self.sftp.chdir(pwd)
   
            files = self.filepath[0]
            
            basenames = 'EliTech_Script'
            self.sftp.put(files, basenames, callback=self.log_transfer2)
                             
            self.filepath = ''
            self.channel.send('chmod 755 ' + basenames + '\n')
            self.channel.send('dos2unix ' + basenames + '\n')
            self.channel.send('./' + basenames + '\n')
            
           ##print basenames    
        except Exception, e:
           ##print 'loi 1',e
            wx.MessageBox("Can't run this script ", 'Error', wx.OK)
            self.channel.send('\n')
            self.filepath = ''
            self.runScript = False
            self.text.Enable(True)
            pass

    def log_transfer2(self, transferred, toBeTransferred):
        pass
    
    def LoadFont(self):
        try:
            gdi32 = WinDLL("gdi32.dll")
            fonts = [font for font in os.listdir("fonts") if font.endswith("otf") or font.endswith("ttf") or font.endswith("ttc")]
            for font in fonts:
                gdi32.AddFontResourceA(os.path.join("fonts", font))
                ######print font
            ######print 'Load Font Successfull'
        except Exception:
            pass
            ######print type(e)
            ######print e
            
    def OnSize(self, evt):
        # for normal size events
        self.isresize = True
#        self.text.SetInsertionPoint(self.text.GetInsertionPoint())
        self.text.SetFocus()
        evt.Skip()
    

    def SetInsertpoint(self, col, row):
        try:
            if row > self.text.GetNumberOfLines() - 1:
                insertline = '\r\n' * (row - (self.text.GetNumberOfLines() - 1))
                self.text.AppendText(insertline)
            
            lineleng = self.text.GetLineLength(row)
            if lineleng < col:
                numspace = ' ' * (col - lineleng)
                self.text.SetInsertionPoint(self.text.XYToPosition(lineleng, row))
                self.text.WriteText(numspace)
            self.text.SetInsertionPoint(self.text.XYToPosition(col, row))
        except Exception, e:
            ##print 'Loi Setinsertpoint'
            ##print e
            pass
        '''
        self.text.SetInsertionPoint(self.text.XYToPosition(col,row))
        x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
        if row != y:
            self.text.SetInsertionPoint(self.text.XYToPosition(0,row))
            x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
            while row != y:
                self.text.AppendText('\r\n')
                self.text.SetInsertionPoint(self.text.XYToPosition(0,row))
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())                    
        
        if col != x:
            textline = self.text.GetLineText(row)
            numspace = ' ' * (col - textline.__len__())
            self.text.SetInsertionPoint(self.text.XYToPosition(textline.__len__(),row))
            self.text.WriteText(numspace)
            self.text.SetInsertionPoint(self.text.XYToPosition(col,row))      
        '''  
    
    def SubCodeR(self, string):
        try:
            strings = string.split('\r')
            for i in range(len(strings)):
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                lengtext = strings[i].__len__()
                lengline = int(x) + int(lengtext)
                textreplace = self.text.GetRange(self.text.GetInsertionPoint(), self.text.GetInsertionPoint() + lengtext)
                indexend = re.search(r'\n', textreplace)
                if indexend != None:
                    indexend = indexend.start()
                    self.text.Replace(self.text.GetInsertionPoint(), self.text.GetInsertionPoint() + indexend, strings[i])
                else:
                    self.text.Replace(self.text.GetInsertionPoint(), self.text.GetInsertionPoint() + lengtext, strings[i])
                if i < len(strings) - 1:
                    rx, ry = self.text.PositionToXY(self.text.GetInsertionPoint())
                    if lengline == int(self.colpaper) + 1:
                        if ry == self.text.GetNumberOfLines() - 1:
                            self.text.WriteText('\r')
                        else:
                            self.text.SetInsertionPoint(self.text.XYToPosition(0, ry + 1))
                    else:
                        self.text.SetInsertionPoint(self.text.XYToPosition(0, ry))
        except Exception, e:
           ##print e
            pass

    
    def SubCVCode(self, seal, string):
        try:
            if seal != None:
                seal = seal.group()
            else:
                seal = ''

            if len(string) == len(seal):
                return
            
            string = string.replace(seal, '', 1)
            if len(string) == 0:
                    return
            #\x08 - Xy ly ki tu \x08 o dau chuoi
            while string[0] == '':
                string = string[1:]
                self.text.SetInsertionPoint(self.text.GetInsertionPoint() - 1)
                if len(string) == 0:
                    return

            flag = False
            if string[-2:] == '\r\n':
                flag = True
            splitX08 = string.split('')
            for j in range(len(splitX08)):
                strings = splitX08[j].split('\r\n')
                for i in range(len(strings)):
                    try:
                        x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                        if (i != len(strings) - 1) :
                            if len(strings[i]) > 0:
                                self.SubCodeR(strings[i])
                                
        
                            if self.numend + self.frow - 1 == y:
                                x1, y1 = self.text.PositionToXY(self.text.GetInsertionPoint())
                                self.SetInsertpoint(self.text.GetLineLength(y1) , y1)
                                self.text.WriteText('\r\n')
                                #Chua xy ly xoa nhieu dau dong cho viec tu dong day dong xuong cua textctrl
                                if self.numstart > 1:
                                    linedel = self.numstart + self.frow - 1;
                                    self.text.Remove(self.text.XYToPosition(0, linedel), self.text.XYToPosition(0, linedel + 1))
                                    self.SetInsertpoint(0, y1)
                                else:
                                    self.frow = self.frow + 1 + (y1 - y)
                            else:
                                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                                self.SetInsertpoint(0, y + 1)
#                            if re.search('ERROR',strings[i]) != None:
#                                self.stoppoint = False
#                                return
#                            #####print self.text.PositionToXY(self.text.GetInsertionPoint())
#                            if self.text.GetLineText(self.text.GetNumberOfLines()-2).find('%') > -1:
#                                    self.stoppoint = False
#                                    return
#                            if self.text.GetLineText(self.text.GetNumberOfLines()-3).find('%') > -1:
#                                    self.stoppoint = False
#                                    return
            
                        else :
                            if flag:
                                break
                            self.SubCodeR(strings[i])
                    except Exception, e:
                        #####print type(e)
                        #####print e
                        self.stoppoint = True
                        wx.MessageBox(str(e), "Subcv 5...", wx.OK)
                        wx.MessageBox(seal, "Subcv 5...", wx.OK)
                if j < len(splitX08) - 1:          
                    self.text.SetInsertionPoint(self.text.GetInsertionPoint() - 1)
        except Exception, e:
            #####print 'Loi o day ne'
            #####print type(e)
            #####print e
            wx.MessageBox(str(e), "Subcv...", wx.OK)
            wx.MessageBox(seal, "Subcv...", wx.OK)

            pass
        
    def ConvertCode(self, data):
        if not self.stoppoint:
                    return
        #####print 'convertcode'
        if self.text.NumberOfLines > self.rowpaper:
            self.frow = self.text.NumberOfLines - self.rowpaper
            #####print 'frow....tinh...', self.text.NumberOfLines, self.rowpaper
        else:
            self.frow = 0
        try:
            ##print 'data nhan duoc ban dau...\n', data
#            #####print list(data)
#            ###print 'frow...',self.frow
            
            
            
            #\x0f - \x07 - \x13 - \x05 - \x02 - \x18
            data = re.sub('|||||', '', data)
            if len(data) == 0:
                return
            
            #\x00 - Loai bo ki tu \x00
            data = re.sub('\x00'.encode(), '', data)
            if len(data) == 0:
                return
            
            #\x08 - Thuc thi ki tu \x08 o dau chuoi data
            while data[0] == '':
                data = data[1:]
                self.text.SetInsertionPoint(self.text.GetInsertionPoint() - 1)
                if len(data) == 0:
                    return
            #\x1b - Xu ly data khi ki tu bat dau khong phai la \x1b        
            if data[0] != '':
                string = re.search(r'^.*?', data, re.DOTALL)
                if string != None:
                    string = string.group()[:-1]
                    self.SubCVCode(None, string)
                    data = data.replace(string, '', 1)
                else:
                    self.SubCVCode(None, data)
                    return
                '''    
                elif self.VIlevel != 4:
                    self.SubCVCode(None, data)
                    return'''
                
            #\x1b -> \x1b tiep theo
            string = re.search(r'.*?', data, re.DOTALL)        
            while string != None:
                if not self.stoppoint:
                    return                
                #####print 'string dau xet', string.group()
                string = string.group()[:-1]
                data = data.replace(string, '', 1)
                
                #\x1b[?1h
                seal = re.search(r'\[\?1h', string)
                if seal != None:
#                    self.dynamis_name = 'VI'
#                    self.VIlevel = 2
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b[?1l
                seal = re.search(r'\[\?1l', string)
                if seal != None:            
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b>
                seal = re.search(r'>', string)
                if seal != None:            
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b=
                seal = re.search(r'=', string)
                if seal != None:
                    ######print 'seal.....',seal.group()            
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b[(int)G
                seal = re.search(r'\[[\d]*G', string)
                if seal != None:
                    ######print 'seal.....',seal.group()            
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b[A
                seal = re.search(r'\[A', string)
                if seal != None:
                    x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                    self.text.SetInsertionPoint(self.text.XYToPosition(x, y - 1))          
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                #\x1b[B
                seal = re.search(r'\[B', string)
                if seal != None:
                    x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                    if y == self.text.GetNumberOfLines() - 1:
                        self.text.AppendText('\r\n')
                    self.text.SetInsertionPoint(self.text.XYToPosition(x, y + 1))          
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                #\x1b[C
                seal = re.search(r'\[C', string)
                if seal != None:
                    x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                    if x == self.text.GetLineLength(y):
                        self.SetInsertpoint(0, y + 1)
                    else:
                        self.text.SetInsertionPoint(self.text.XYToPosition(x + 1, y))          
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                #\x1b[D
                seal = re.search(r'\[D', string)
                if seal != None:
                    x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                    if x == 1:
                        self.text.SetInsertionPoint(self.text.XYToPosition(self.text.GetLineLength(y - 1), y - 1))
                    else:
                        self.text.SetInsertionPoint(self.text.XYToPosition(x - 1, y))          
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b[(int)...m
                seal = re.search(r'\[[0-9;]*m', string)
                if seal != None:
                    #####print 'co vao day'
                    strings = seal.group()[2:-1]
                    forcolor = 'BLACK'
                    backcolor = 'WHITE'
                    if strings == '':
                        self.text.SetDefaultStyle(wx.TextAttr(forcolor, backcolor, self.fontb))
                        self.SubCVCode(seal, string)
                        string = re.search(r'.*?', data, re.DOTALL)
                        continue 
                    #####print strings
                    strings = strings.split(';') 
                    for i in range(len(strings)):
                        num = int(strings[i])
                        if num == 30:
                            forcolor = 'BLACK'
                        elif num == 31:
                            forcolor = 'RED'
                        elif num == 32:
                            forcolor = 'GREEN'
                        elif num == 33:
                            forcolor = 'YELLOW'
                        elif num == 34:
                            forcolor = 'BLUE'
                        elif num == 35:
                            forcolor = 'MAGENTA'
                        elif num == 36:
                            forcolor = 'CYAN'
                        elif num == 37:
                            forcolor = 'WHITE'
                            
                        elif num == 40:
                            backcolor = 'BLACK' 
                        elif num == 41:
                            backcolor = 'RED'
                        elif num == 42:
                            backcolor = 'GREEN'
                        elif num == 43:
                            backcolor = 'YELLOW'
                        elif num == 44:
                            backcolor = 'BLUE'
                        elif num == 45:
                            backcolor = 'MAGENTA'
                        elif num == 46:
                            backcolor = 'CYAN'
                        elif num == 47:
                            backcolor = 'WHITE'
                        
                        elif num == 0:
                            forcolor = 'BLACK'
                            backcolor = 'WHITE'
                        elif num == 1:
                            forcolor = 'BLUE'
                            backcolor = 'WHITE'
                        elif num == 7:
                            forcolor = 'WHITE'
                            backcolor = 'BLACK'
                        else:
                            forcolor = 'BLACK'
                            backcolor = 'WHITE'
                            
                    self.text.SetDefaultStyle(wx.TextAttr(forcolor, backcolor, self.fontb))
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1bM
                seal = re.search(r'M', string)
                if seal != None:
                    #####print 'numend + numstart',self.numend,self.numstart
                    indexrow = self.numend + self.frow - 1
                    lengtext = self.text.GetLineText(indexrow).__len__()
                    flag = False
                    if indexrow < self.text.GetNumberOfLines() - 1:
                        flag = True
                    if flag:
                        self.text.Remove(self.text.XYToPosition(0, indexrow), self.text.XYToPosition(0, indexrow) + lengtext + 1)
                    else:
                        self.text.Remove(self.text.XYToPosition(0, indexrow) - 1, self.text.XYToPosition(0, indexrow) + lengtext)           
                    indexrow = self.numstart + self.frow - 1
                    if flag:
                        self.text.SetInsertionPoint(self.text.XYToPosition(0, indexrow))
                    else:
                        self.text.SetInsertionPoint(self.text.XYToPosition(0, indexrow - 1))
                    self.text.WriteText('\r\n')    
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b[(int);(int)r
                seal = re.search(r'\[[\d]*;[\d]*r', string)
                if seal != None:
                    numstart = re.search(r'[\d]*;', seal.group()).group()
                    numstart = numstart[:-1]
                    numend = re.search(r';[\d]*r', seal.group()).group()
                    numend = numend[1:-1]
                    self.numend = int(numend)
                    self.numstart = int(numstart)  
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue            
                
                #\x1b[H
                seal = re.search(r'\[H', string)
                if seal != None:
#                    if self.firstrun:
#                        x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
#                        text = '\r\n' * self.rowpaper
#                        self.text.AppendText(text)
#                        if self.text.NumberOfLines > self.rowpaper:
#                            self.frow = self.text.NumberOfLines - self.rowpaper
#                        else:
#                            self.frow = 0

                    #####print 'self.frow...',self.frow    
                    self.text.SetInsertionPoint(self.text.XYToPosition(0, self.frow))
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b[J
                seal = re.search(r'\[J', string)
                if seal != None:
                    x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                    x1, y1 = self.text.PositionToXY(self.text.GetLastPosition())
                    self.text.Remove(self.text.GetInsertionPoint(), self.text.GetLastPosition())
                    insertrow = '\r\n' * (y1 - y)
                    self.text.AppendText(insertrow)
                    self.text.SetInsertionPoint(self.text.XYToPosition(x, y))
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    ######print 'data sau khi chay J',list(self.text.GetRange(self.text.XYToPosition(0,0),self.text.GetLastPosition()))
                    continue
                
                #\x1b[(int);(int)H
                seal = re.search(r'\[[\d]*;[\d]*H', string)
                if seal != None:
                    row = re.search(r'[\d]*;', seal.group()).group()
                    row = row[:-1]
                    col = re.search(r';[\d]*H', seal.group()).group()
                    col = col[1:-1]
                    try:
                        row = int(row) + self.frow - 1
                        col = int(col) - 1
                        self.SetInsertpoint(col, row)
                    except Exception, e:
                        pass
                    self.xtemp, self.ytemp = self.text.PositionToXY(self.text.GetInsertionPoint())                    
                    self.pointsave = self.text.GetInsertionPoint()
                    
                    
                    
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                
                #\x1b[K
                seal = re.search(r'\[K', string)
                if seal != None:
                    x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                    textdel = self.text.GetLineText(y)
                    textdel = textdel[x:]
                    self.text.Remove(self.text.GetInsertionPoint(), self.text.GetInsertionPoint() + textdel.__len__())
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                   
                
                
                seal = re.search(r'\[[\d]*C', string)
                if seal != None:
                    num = seal.group()[2:]
                    num = num[:-1]
                    num = int(num)
                    x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                    index = x + num
                    self.text.SetInsertionPoint(self.text.XYToPosition(index, y))
                    x1, y1 = self.text.PositionToXY(self.text.GetInsertionPoint())

                    if x1 != index:
                        textline = self.text.GetLineText(y)
                        numspace = ' ' * (index - textline.__len__())
                        self.text.SetInsertionPoint(self.text.XYToPosition(textline.__len__(), y))
                        self.text.WriteText(numspace)
                        self.text.SetInsertionPoint(self.text.XYToPosition(index, y))

                    self.SubCVCode(seal, string) 
                    string = re.search(r'.*?', data, re.DOTALL)
                    continue
                ##############################################################################################################
                #####print "khong tim ra dinh dang thich hop", string
                self.text.AppendText(string)
                string = re.search(r'.*?', data, re.DOTALL)
                ##############################################################################################################
           
            #Khong tim thay chuoi \x1b -> x1b: chi con lai \x1b+data
            string = data
            #######print 'thoat khoi vong lap',string
            seal = re.search(r'\[\?1h', string)
            if seal != None:
#                self.dynamis_name='VI'
#                self.VIlevel = 2
                self.SubCVCode(seal, string)
                return
            
            #\x1b[?1l
            seal = re.search(r'\[\?1l', string)
            if seal != None:            
                self.SubCVCode(seal, string)
                return
            
            #\x1b>
            seal = re.search(r'>', string)
            if seal != None:            
                self.SubCVCode(seal, string)
                return
            
            #\x1b=
            seal = re.search(r'=', string)
            if seal != None:
                self.SubCVCode(seal, string)
                return
                        
            #\x1b[(int)G
            seal = re.search(r'\[[\d]*G', string)
            if seal != None:
                ######print 'seal.....',seal.group()            
                self.SubCVCode(seal, string)
                return
            
            #\x1b[A
            seal = re.search(r'\[A', string)
            if seal != None:
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                self.text.SetInsertionPoint(self.text.XYToPosition(x, y - 1))          
                self.SubCVCode(seal, string)
                string = re.search(r'.*?', data, re.DOTALL)
                return
            #\x1b[B
            seal = re.search(r'\[B', string)
            if seal != None:
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                if y == self.text.GetNumberOfLines() - 1:
                    self.text.AppendText('\r\n')
                self.text.SetInsertionPoint(self.text.XYToPosition(x, y + 1))          
                self.SubCVCode(seal, string)
                string = re.search(r'.*?', data, re.DOTALL)
                return
            #\x1b[C
            seal = re.search(r'\[C', string)
            if seal != None:
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                if x == self.text.GetLineLength(y):
                    self.SetInsertpoint(0, y + 1)
                else:
                    self.text.SetInsertionPoint(self.text.XYToPosition(x + 1, y))          
                self.SubCVCode(seal, string)
                string = re.search(r'.*?', data, re.DOTALL)
                return
            #\x1b[D
            seal = re.search(r'\[D', string)
            if seal != None:
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                if x == 1:
                    self.text.SetInsertionPoint(self.text.XYToPosition(self.text.GetLineLength(y - 1), y - 1))
                else:
                    self.text.SetInsertionPoint(self.text.XYToPosition(x - 1, y))          
                self.SubCVCode(seal, string)
                string = re.search(r'.*?', data, re.DOTALL)
                return
            
            #\x1b[(int)...m
            seal = re.search(r'\[[0-9;]*m', string)
            if seal != None:
                #####print 'co vao day'
                strings = seal.group()[2:-1]
                forcolor = 'BLACK'
                backcolor = 'WHITE'
                if strings == '':
                    self.text.SetDefaultStyle(wx.TextAttr(forcolor, backcolor, self.fontb))
                    self.SubCVCode(seal, string)
                    string = re.search(r'.*?', data, re.DOTALL)
                    return 
                #####print strings
                strings = strings.split(';') 
                for i in range(len(strings)):
                    num = int(strings[i])
                    if num == 30:
                        forcolor = 'BLACK'
                    elif num == 31:
                        forcolor = 'RED'
                    elif num == 32:
                        forcolor = 'GREEN'
                    elif num == 33:
                        forcolor = 'YELLOW'
                    elif num == 34:
                        forcolor = 'BLUE'
                    elif num == 35:
                        forcolor = 'MAGENTA'
                    elif num == 36:
                        forcolor = 'CYAN'
                    elif num == 37:
                        forcolor = 'WHITE'

                        
                    elif num == 40:
                        backcolor = 'BLACK' 
                    elif num == 41:
                        backcolor = 'RED'
                    elif num == 42:
                        backcolor = 'GREEN'
                    elif num == 43:
                        backcolor = 'YELLOW'
                    elif num == 44:
                        backcolor = 'BLUE'
                    elif num == 45:
                        backcolor = 'MAGENTA'
                    elif num == 46:
                        backcolor = 'CYAN'
                    elif num == 47:
                        backcolor = 'WHITE'
                    
                    elif num == 0:
                        forcolor = 'BLACK'
                        backcolor = 'WHITE'
                    elif num == 1:
                        forcolor = 'BLUE'
                        backcolor = 'WHITE'
                    elif num == 7:
                        forcolor = 'WHITE'
                        backcolor = 'BLACK'
                    else:
                        forcolor = 'BLACK'
                        backcolor = 'WHITE'
                        
                self.text.SetDefaultStyle(wx.TextAttr(forcolor, backcolor, self.fontb))
                self.SubCVCode(seal, string)
                return
            
            #\x1bM
            seal = re.search(r'M', string)
            if seal != None:
                #####print 'numend + numstart',self.numend,self.numstart
                indexrow = self.numend + self.frow - 1
                lengtext = self.text.GetLineText(indexrow).__len__()
                flag = False
                if indexrow < self.text.GetNumberOfLines() - 1:
                    flag = True
                if flag:
                    self.text.Remove(self.text.XYToPosition(0, indexrow), self.text.XYToPosition(0, indexrow) + lengtext + 1)
                else:
                    self.text.Remove(self.text.XYToPosition(0, indexrow) - 1, self.text.XYToPosition(0, indexrow) + lengtext)           
                indexrow = self.numstart + self.frow - 1
                if flag:
                    self.text.SetInsertionPoint(self.text.XYToPosition(0, indexrow))
                else:
                    self.text.SetInsertionPoint(self.text.XYToPosition(0, indexrow - 1))
                self.text.WriteText('\r\n')    
                self.SubCVCode(seal, string)
                return
            
            #\x1b[(int);(int)r
            seal = re.search(r'\[[\d]*;[\d]*r', string)
            if seal != None:
                numstart = re.search(r'[\d]*;', seal.group()).group()
                numstart = numstart[:-1]
                numend = re.search(r';[\d]*r', seal.group()).group()
                numend = numend[1:-1]
                self.numend = int(numend)
                self.numstart = int(numstart)  
                self.SubCVCode(seal, string)
                return            
            
            #\x1b[H
            seal = re.search(r'\[H', string)
            if seal != None:
#                if self.firstrun:
#                    x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
#                    text = '\r\n' * self.rowpaper
#                    self.text.AppendText(text)
#                    if self.text.NumberOfLines > self.rowpaper:
#                        self.frow = self.text.NumberOfLines - self.rowpaper
#                    else:
#                        self.frow = 0

                    
                self.text.SetInsertionPoint(self.text.XYToPosition(0, self.frow))
                self.SubCVCode(seal, string)
                return
            
            #\x1b[J
            seal = re.search(r'\[J', string)
            if seal != None:
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                x1, y1 = self.text.PositionToXY(self.text.GetLastPosition())
                self.text.Remove(self.text.GetInsertionPoint(), self.text.GetLastPosition())
                insertrow = '\r\n' * (y1 - y)
                self.text.AppendText(insertrow)
                self.text.SetInsertionPoint(self.text.XYToPosition(x, y))
                self.SubCVCode(seal, string)
                return
            
            #\x1b[(int);(int)H
            seal = re.search(r'\[[\d]*;[\d]*H', string)
            #####print ' vao duoc day roi'
            if seal != None:
                row = re.search(r'[\d]*;', seal.group()).group()
                row = row[:-1]
                col = re.search(r';[\d]*H', seal.group()).group()
                col = col[1:-1]
                try:
                    row = int(row) + self.frow - 1
                    col = int(col) - 1
                    self.SetInsertpoint(col, row)
                except Exception, e:
                    pass
                self.xtemp, self.ytemp = self.text.PositionToXY(self.text.GetInsertionPoint())                    
                self.pointsave = self.text.GetInsertionPoint()
                
                self.SubCVCode(seal, string)
                return
            
            #\x1b[K
            seal = re.search(r'\[K', string)
            if seal != None:
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                textdel = self.text.GetLineText(y)
                textdel = textdel[x:]
                self.text.Remove(self.text.GetInsertionPoint(), self.text.GetInsertionPoint() + textdel.__len__())
                self.SubCVCode(seal, string)
                return
               
            
            
            seal = re.search(r'\[[\d]*C', string)
            if seal != None:
                num = seal.group()[2:]
                num = num[:-1]
                num = int(num)
                x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
                index = x + num
                self.text.SetInsertionPoint(self.text.XYToPosition(index, y))
                x1, y1 = self.text.PositionToXY(self.text.GetInsertionPoint())

                if x1 != index:
                    textline = self.text.GetLineText(y)
                    numspace = ' ' * (index - textline.__len__())
                    self.text.SetInsertionPoint(self.text.XYToPosition(textline.__len__(), y))
                    self.text.WriteText(numspace)
                    self.text.SetInsertionPoint(self.text.XYToPosition(index, y))

                self.SubCVCode(seal, string) 
                return
            
            seal = re.search(r'-B?', string)
            if seal != None:
                self.SubCVCode(seal, string) 
                return
            ######print 'do khong ra cau lenh hop le...', string
            
            self.codeteamp = string + self.codeteamp
            if re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\]. $', self.codeteamp):
                seal = re.search(r'', self.codeteamp)
                if seal != None:
                    self.SubCVCode(seal, self.codeteamp) 
                    self.codeteamp = ''
            #print self.codeteamp
            #print list(self.codeteamp)
            #wx.MessageBox(self.codeteamp,'notice',wx.OK)
        except Exception, e:
            #####print type(e)
            wx.MessageBox(str(e), "ConvertCode...", wx.OK)
            wx.MessageBox(string, "ConvertCode...", wx.OK)
        
            
                
        

    def OnIdle(self, evt):
        if self.flagFindDialog:
            self.text.SetFocus()
        
        if self.isconnect:
            
            if self.isresize == True:
                #####print float(self.panel.GetSize().y-self.toolbar.GetSize().y-22)/float(self.text.GetCharHeight()) + 2.0
                
                
                rowpaper = float(self.panel.GetSize().y - self.toolbar.GetSize().y - 22) / float(self.text.GetCharHeight()) + 2.0
                mod = rowpaper - int(rowpaper)
                ##print 'mod...', mod
                ##print 'row...',rowpaper
                if mod < 0.6:
                    rowpaper -= 1
                rowpaper = int(rowpaper)
                colpaper = self.text.GetSize().x / self.text.GetCharWidth() + 2
                self.channel.resize_pty(width=colpaper, height=rowpaper)
                self.rowpaper = rowpaper 
                self.colpaper = colpaper
                self.numend = self.rowpaper
                self.isresize = False
                self.UpdateStatusBar3()
                ###print 'row,col',rowpaper,colpaper
                


    def UpdateStatusBar4(self):
        self.statusbar.SetStatusText(self.term, 4)
        
    def UpdateStatusBar5(self):
        if wx.GetKeyState(wx.WXK_CAPITAL):
            self.statusbar.SetStatusText("CAP", 5)
        else:
            self.statusbar.SetStatusText("", 5)
        
    def UpdateStatusBar6(self):
        if wx.GetKeyState(wx.WXK_NUMLOCK):
            self.statusbar.SetStatusText("NUM", 6)
        else:
            self.statusbar.SetStatusText("", 6)
                
    def UpdateStatusBar3(self):
        self.statusbar.SetStatusText(str(int(self.rowpaper)) + ' Rows, ' + str(self.colpaper) + ' Cols', 3)
        

             
    def UpdateStatusBar2(self):
        
        numline = self.text.GetNumberOfLines()
        self.col, self.row = self.text.PositionToXY(self.text.GetInsertionPoint())
        if numline > self.rowpaper:
            self.row = self.rowpaper - (numline - self.row) + 1
        else:
            self.row = self.row + 1
        self.col = self.col + 1
        self.statusbar.SetStatusText(str(self.row) + ', ' + str(self.col), 2)
    
    def OnFindAct(self, event):
        #self.codePage : wx.Panel
        #self.codePage.editor : wx.TextCtrl
        editor = self.text
#        self.nb.SetSelection(1)
        end = editor.GetLastPosition()
        textstring = editor.GetRange(0, end).lower() # get conetents of TextCtrl
        findstring = self.finddata.GetFindString().lower() # self.finddata = wx.FindReplaceData()
        backward = not (self.finddata.GetFlags() & wx.FR_DOWN)
        if backward:
            start = (self.downPoint, self.upPoint)[0]
            #print 'start1',start
            loc = textstring.rfind(findstring, 0, start)
        else:
            start = (self.downPoint, self.upPoint)[1]
            #print 'start2',start
            loc = textstring.find(findstring, start)
        
        if loc == -1 and start != 0:
            # string not found, start at beginning
            if backward:
                start = end
                loc = textstring.rfind(findstring, 0, start)
            else:
                start = 0
                loc = textstring.find(findstring, start)
        
        if loc == -1:
            dlg = wx.MessageDialog(self, 'Find String Not Found',
                          'Find String Not Found in Demo File',
                          wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
        '''
        if self.findDlg:
            if loc == -1:
                self.findDlg.SetFocus()
                return
            else:
                self.findDlg.Destroy()
                self.findDlg = None
                '''
        
        editor.ShowPosition(loc)
        self.text.SetStyle(self.downPoint, self.upPoint, wx.TextAttr(wx.NullColour, 'WHITE', self.fontb))
        self.downPoint = loc
        self.upPoint = loc + len(findstring)
#        editor.SetSelection(loc, loc + len(findstring))
        self.text.SetStyle(self.downPoint, self.upPoint, wx.TextAttr(wx.NullColour, 'CYAN', self.fontb))
        
    def OnFindClose(self, event):
        self.flagFindDialog = True
        self.findDlg.Destroy()
        self.text.SetInsertionPoint(self.indexfind)
    
    def OnContextMenu(self, event):
        if self.isconnect == False:
            return

        if not hasattr(self, "popupID1"):
            self.popupID1 = wx.NewId()
            self.popupID2 = wx.NewId()
            self.popupID3 = wx.NewId()
            self.popupID4 = wx.NewId()
            self.popupID5 = wx.NewId()
            self.popupID6 = wx.NewId()
            self.popupID7 = wx.NewId()
            self.popupID8 = wx.NewId()
            
            self.Bind(wx.EVT_MENU, self.OnCopy, id=self.popupID1)
            self.Bind(wx.EVT_MENU, self.OnPaste, id=self.popupID2)
            self.Bind(wx.EVT_MENU, self.OnCopyAPaste, id=self.popupID3)
            self.Bind(wx.EVT_MENU, self.OnOpenURL, id=self.popupID4)
            self.Bind(wx.EVT_MENU, self.OnFind, id=self.popupID5)
            self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupID6)
            self.Bind(wx.EVT_MENU, self.OnClearScrollback, id=self.popupID7)
            self.Bind(wx.EVT_MENU, self.OnClearScreen, id=self.popupID8)
            


        # make a menu
        self.menupopup = wx.Menu()
        # Show how to put an icon in the menu
        
        
        item = wx.MenuItem(self.menupopup, self.popupID1, "Copy")
#        bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_MENU, (24,24))
#        item.SetBitmap(bmp)
        self.menupopup.AppendItem(item)
        
        item = wx.MenuItem(self.menupopup, self.popupID2, "Paste")
#        bmp = wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_MENU, (24,24))
#        item.SetBitmap(bmp)
        self.menupopup.AppendItem(item)
        
        item = wx.MenuItem(self.menupopup, self.popupID3, "Copy && Paste")
#        bmp = wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_MENU, (24,24))
#        item.SetBitmap(bmp)
        self.menupopup.AppendItem(item)
        
        self.menupopup.AppendSeparator()
        
        item = wx.MenuItem(self.menupopup, self.popupID4, "Open URL")
#        bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_MENU, (24,24))
#        item.SetBitmap(bmp)
        self.menupopup.AppendItem(item)
        
        self.menupopup.AppendSeparator()
        
        item = wx.MenuItem(self.menupopup, self.popupID5, "Find...")
#        bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_MENU, (24,24))
#        item.SetBitmap(bmp)
        self.menupopup.AppendItem(item)
        
        item = wx.MenuItem(self.menupopup, self.popupID6, "Select All")
#        bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_MENU, (24,24))
#        item.SetBitmap(bmp)
        self.menupopup.AppendItem(item)
        
        self.menupopup.AppendSeparator()
        
        item = wx.MenuItem(self.menupopup, self.popupID7, "Clear Scrollback")
#        bmp = wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_MENU, (24,24))
#        item.SetBitmap(bmp)
        self.menupopup.AppendItem(item)
        
        item = wx.MenuItem(self.menupopup, self.popupID8, "Clear Screen")
#        bmp = wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_MENU, (24,24))
#        item.SetBitmap(bmp)
        self.menupopup.AppendItem(item)

        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        
        self.UpdateStatusPopupMN()
        self.PopupMenu(self.menupopup)
        self.menupopup.Destroy()
        
    def UpdateStatusPopupMN(self):
        if not wx.TheClipboard.IsOpened():  # may crash, otherwise
            do = wx.TextDataObject()
            wx.TheClipboard.Open()
            success = wx.TheClipboard.GetData(do)
            wx.TheClipboard.Close()
            self.menupopup.FindItemById(self.popupID2).Enable(success)
            ######print self.text.GetStringSelection()
            if self.downPoint == -1 or self.upPoint == -1 or self.downPoint == self.upPoint:
                self.menupopup.FindItemById(self.popupID1).Enable(False)
                self.menupopup.FindItemById(self.popupID3).Enable(False)
            else:
                self.menupopup.FindItemById(self.popupID1).Enable(True)
                self.menupopup.FindItemById(self.popupID3).Enable(True)
        
        if not self.flagLink:
            self.menupopup.FindItemById(self.popupID4).Enable(True)
        else:
            self.menupopup.FindItemById(self.popupID4).Enable(False)
            
        
    def OnCopyAPaste(self, event):
        self.OnCopyAndPaste(None)
        
    def OnOpenURL(self, event):
        webbrowser.open(self.link)
        
    
    def OnFind(self, event):
#        if re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].*', self.text.GetLineText(self.text.GetNumberOfLines()-1), re.DOTALL)==None:
#            wx.MessageBox("Stop your current process.", "Notice", wx.OK|wx.ICON_INFORMATION)
#            return
        if self.flagFindDialog:
            self.flagFindDialog = False
            self.downPoint = self.text.GetInsertionPoint()
            self.upPoint = self.text.GetInsertionPoint()
            self.finddata = wx.FindReplaceData()
            self.findDlg = wx.FindReplaceDialog(self, self.finddata, "Find")
            self.findDlg.data = self.finddata  # save a reference to it...
            self.findDlg.Show(True)
            self.indexfind = self.text.GetInsertionPoint()
        else:
            self.findDlg.SetFocus()
    
    def OnSelectAll(self, event):
        index = self.text.GetInsertionPoint()
        self.downPoint = 0
        self.upPoint = self.text.GetLastPosition()
        self.text.SetStyle(self.downPoint, self.upPoint, wx.TextAttr(wx.NullColour, '#3399ff', self.fontb))


    
    def OnClearScrollback(self, event):
        if self.frow < 2:
            return
        self.updatePosition(0, self.frow)
        
    
    def OnClearScreen(self, event):
        self.text.AppendText('\n' * self.rowpaper)
        indexrow = self.text.GetNumberOfLines() - self.rowpaper
        self.text.SetInsertionPoint(self.text.XYToPosition(0, indexrow))
        if self.text.NumberOfLines > self.rowpaper:
            self.frow = self.text.NumberOfLines - self.rowpaper
            #####print 'frow....tinh...', self.text.NumberOfLines, self.rowpaper
        else:
            self.frow = 0
      
    def OnCopy(self, event):
        if not wx.TheClipboard.IsOpened():
            wx.TheClipboard.Open()
            do = wx.TextDataObject()
            if self.downPoint < self.upPoint:
                ###print self.text.GetRange(self.downPoint, self.upPoint)
                do.SetText(self.text.GetRange(self.downPoint, self.upPoint))
            else:
                ###print self.text.GetRange(self.downPoint, self.upPoint)
                do.SetText(self.text.GetRange(self.upPoint, self.downPoint))
            wx.TheClipboard.SetData(do)
            wx.TheClipboard.Close()
    
    def OnPaste(self, event):
         if not wx.TheClipboard.IsOpened():
            wx.TheClipboard.Open()
            do = wx.TextDataObject()
            wx.TheClipboard.GetData(do)
            self.channel.send(do.GetText())
            wx.TheClipboard.Close()  

    
    def OnCopyAndPaste(self, event): 
         if not wx.TheClipboard.IsOpened():
            wx.TheClipboard.Open()
            do = wx.TextDataObject()
            if self.downPoint < self.upPoint:
                ###print self.text.GetRange(self.downPoint, self.upPoint)
                do.SetText(self.text.GetRange(self.downPoint, self.upPoint))
            else:
                ###print self.text.GetRange(self.downPoint, self.upPoint)
                do.SetText(self.text.GetRange(self.upPoint, self.downPoint))
            wx.TheClipboard.SetData(do)  
            self.channel.send(do.GetText())
            wx.TheClipboard.Close()   
    
    def OnDisUp(self, event):
        if self.dynamis_name == 'VI':
            #####print "upvi"
            self.keypress = 'up'
            #####print 'OnDisUp'
            event.Skip()
            
            '''currentIndex = str(self.text.index('insert'))
            topIndex = str(self.topIndex)                       
            if(int(currentIndex.split('.')[0]) <= int(topIndex.split('.')[0])):
                return 'break'
            x,y,width,height,baseline= self.text.dlineinfo('insert')                                        
            #######print y
            if y==2: 
                self.endIndex = str(float(self.endIndex)-1)'''
                #######print self.endIndex
        elif self.dynamis_name == 'COMMAND': 
            self.channel.send('OA')
            return 
        
        else:
            return 'break'

    def OnDisDown(self, event):
   
  
        if self.dynamis_name == 'COMMAND': 
            self.channel.send('OB')
            return 
        
        else:
            return 'break'
    
    def OnDisLeft(self, event):
#        self.update_insert()
        if self.dynamis_name == 'COMMAND':
            self.channel.send('OD')
            return
        
        else:
            return
    
    def OnDisRight(self, event):
#        self.update_insert()
        if self.dynamis_name == 'COMMAND':
            self.channel.send('OC')
            return
        

        else:
            return
    
    def OnDisBksp(self, event):
#        self.update_insert()
        if self.dynamis_name == 'COMMAND':
            self.channel.send(chr(wx.WXK_BACK))
            return
        
    
        else:
            return
    
    def OnDisDelete(self, event):        
#        self.update_insert()
        ######print 'OnDisDelete'
        if self.dynamis_name == 'COMMAND':
            self.channel.send(chr(wx.WXK_DELETE))
            return
        
     
        else:
            return


    def test(self):
        self.test = 'test'
    
    def update_insert(self):
        insert = self.text.GetInsertionPoint()
        i = 0
        self.insert_temp = insert
        ######print 'current row.....', self.text.PositionToXY(self.text.GetInsertionPoint())
#        while insert<=self.text.GetLastPosition():
#            self.insert_temp=insert
#            
#            insert=65535*i +self.text.GetInsertionPoint() +i
#            i=i+1
#        
#        ######print str(self.text.PositionToXY(self.text.GetInsertionPoint())) + str(self.insert_temp) +" - "+ str(self.indexText) +" - "+ str(self.text.GetLastPosition()) 
    
    
    def DoDrawing(self, event=None, dc=None):
        if dc is None:
            dc = wx.ClientDC(self)
        
        mdc = wx.BufferedDC(dc)
        
        mdc.Clear()
        
        mdc.SetPen(wx.Pen('#d4d4d4', width=0, style=wx.TRANSPARENT))
        
        for group in self.list_of_paintables:
            mdc.SetBrush(wx.Brush(group.color)) # '#c56c00'
            mdc.DrawRectangle(group.x, group.y, group.size_x, group.size_y)
        
        if type(event) == wx.MouseEvent:
            x, y = event.GetPosition()
            mdc.SetPen(wx.Pen(wx.Colour(100, 100, 100), 1, wx.DOT))
            mdc.CrossHair(x, y)
            
        dc.DrawBitmap(mdc.GetAsBitmap(), 0, 0) # Reduces flicker
        
#    def GetBitmap(self):
#        if (self.state & tribler_topButton.MOUSE_OVER) and self.bitmaps[1]:
#            return self.bitmaps[1]
#        return self.bitmaps[0]
        
    def OnPaint(self, evt):
        if self.ready:
            dc = wx.BufferedPaintDC(self)
            dc.SetBackground(wx.Brush(self.backgroundColor))
            dc.Clear()
            
            if self.parentBitmap:
                dc.SetPen(wx.TRANSPARENT_PEN)
                dc.SetBrush(wx.BrushFromBitmap(self.parentBitmap))
                w, h = self.GetClientSize()
                dc.DrawRectangle(0, 0, w, h)
            elif self.parentColor:
                dc.SetPen(wx.TRANSPARENT_PEN)
                dc.SetBrush(wx.Brush(self.parentColor))
                w, h = self.GetClientSize()
                dc.DrawRectangle(0, 0, w, h)
            
            if not self.getEnabled():
                return
    
#            bitmap = self.GetBitmap()
#            if bitmap:
#                dc.DrawBitmap(bitmap, 0,0, True)
             
    def mouser_event(self, event):
        ##############MenuPopup Link#####################
#        print event.Leaving()
        event.Skip()
        return
        if event.Leaving():
            print '....'
            print self.text.GetRect()
            print self.text.GetCapture()
            print self.text.GetUpdateClientRect()
            print self.text.GetBestSizeTuple()
            print event.GetPositionTuple()
            self.top_data.drag()
            
        if event.RightIsDown():

            hit, indexclick = self.text.HitTestPos(event.GetPosition())
            x, y = self.text.PositionToXY(indexclick)
            indexx = x
            linetext = self.text.GetLineText(y)
            
            link = None
            strings = linetext.split(' ')
            lengindex = 0
            for i in range(len(strings)):
                lengindex = lengindex + strings[i].__len__() + 1
                if lengindex - 1 >= x:
                    x = x - (lengindex - strings[i].__len__())
                    lengindex = i
                    break
            #print strings[lengindex]
            if indexx + 5 > len(linetext) - 1:
                linelink = strings[lengindex][:x]
            else:
                linelink = strings[lengindex][:x + 5]
            seal = re.search(r'www.', linelink)
            if seal != None:
                pass
            else:
                seal = re.search(r'ftp://', linelink)
                if seal != None:
                    pass
                else:
                    seal = re.search(r'http://', linelink)
                    if seal != None:
                        pass
                    else:
                        seal = re.search(r'https://', linelink)
                        
            if seal != None:
                seal = seal.start()
                link = strings[lengindex][seal:]

            if link != None:
                self.flagLink = False
                self.link = link
            else:
                self.flagLink = True
                self.link = ""
      
        #################################################
        
        
        if event.Dragging() and event.LeftIsDown(): 
            if self.trendFlag == False and self.downPoint != -1:
                self.trendFlag = True
                hit, self.upPoint = self.text.HitTestPos(event.GetPosition())
                #print 'mouse,GetScrollPos,downPoint,upPoint,previousPoint',self.text.GetScrollPos(wx.VERTICAL),self.downPoint,self.upPoint,self.previousPoint
                mouse1 = self.upPoint
                self.text.Freeze()
                currentScroll = self.text.GetScrollPos(wx.VERTICAL)
                if self.upPoint > self.downPoint:
                    #print 'if',currentScroll
                    if self.previousPoint == -1:
                        self.text.SetStyle(self.downPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'CYAN', self.fontb)))
                    else:
                        if self.previousPoint < self.downPoint:
                            self.text.SetStyle(self.previousPoint, self.downPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                            self.previousPoint = self.downPoint
                        if self.previousPoint < self.upPoint:
                            self.text.SetStyle(self.previousPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'CYAN', self.fontb)))
                        elif self.previousPoint > self.upPoint:
                            self.text.SetStyle(self.previousPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                        else:
                            #print 'pass1',self.previousPoint,self.upPoint
                            pass
                            
                elif self.upPoint < self.downPoint:
                    #print 'else,GetScrollPos,downPoint,upPoint,previousPoint',self.text.GetScrollPos(wx.VERTICAL),self.downPoint,self.upPoint,self.previousPoint
                    if self.previousPoint == -1:
                        #print 'else1'
                        self.text.SetStyle(self.downPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'CYAN', self.fontb)))
                    else:
                        if self.previousPoint > self.downPoint:
                            #print 'else2',self.downPoint ,self.previousPoint
                            self.text.SetStyle(self.downPoint , self.previousPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                            self.previousPoint = self.downPoint
                            
                        if self.previousPoint > self.upPoint:
                            #print 'else3,GetScrollPos,downPoint,upPoint,previousPoint',self.text.GetScrollPos(wx.VERTICAL),self.downPoint,self.upPoint,self.previousPoint
                            self.text.SetStyle(self.previousPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'CYAN', self.fontb)))
                        elif self.previousPoint < self.upPoint:
                            #print 'else4'
                            self.text.SetStyle(self.previousPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                        else:
                            #print 'pass2,GetScrollPos,downPoint,upPoint,previousPoint',self.text.GetScrollPos(wx.VERTICAL),self.downPoint,self.upPoint,self.previousPoint
                            pass    
                else:
                    if self.previousPoint != -1:
                        self.text.SetStyle(self.previousPoint, self.downPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                    else:
                        pass
#                        wx.MessageBox('end','notify',wx.OK)
                while currentScroll < self.text.GetScrollPos(wx.VERTICAL):
                    #print '<',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
                    self.text.ScrollLines(-1)
                      
                while currentScroll > self.text.GetScrollPos(wx.VERTICAL):
                    #print '>',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
                    self.text.ScrollLines(1)
                            
#                if currentScroll != self.text.GetScrollPos(wx.VERTICAL):   
#                    if platform.release()=='XP':
#                        while currentScroll < self.text.GetScrollPos(wx.VERTICAL):
#                            self.text.ScrollLines(-1)
#                              
#                        while currentScroll > self.text.GetScrollPos(wx.VERTICAL):
#                            self.text.ScrollLines(1) 
#                    else:
#                        self.text.ScrollLines((currentScroll/self.text.CharHeight)-(self.text.GetScrollPos(wx.VERTICAL)/self.text.CharHeight))    
                self.text.Thaw()
                if mouse1 != self.upPoint:
                    #print 'mouse,GetScrollPos,downPoint,upPoint,previousPoint',self.text.GetScrollPos(wx.VERTICAL),self.downPoint,self.upPoint,self.previousPoint
                    pass
                self.previousPoint = self.upPoint
                event.Skip()
                self.trendFlag = False
                return
            
        event.Skip()
        return
#        
#        return        
#        
#        if self.dynamis_name == 'TOP':
#            return 'break'
#        
#        elif self.dynamis_name == "VI": 
#            event.Skip()
#        
#        else:
#            return
#            event.Skip()
    def mouser_dclick(self, event):
        ######print event.GetPosition()
        #####print 'mouser_dclick'
        return 'break'
    def mouser_down(self, event):
        #####print 'down'
        event.Skip()
        
    def mouser_up(self, event):
        ######print event.GetPosition()
        #####print 'up'
        event.Skip()
        #self.text.SetSelection(self.down,self.up)
        self.up = 0
        self.down = 0
        
    def rightdown(self, event):
        
        if event.Dragging() and event.RightDown():
            return
        event.Skip()
        
    def drawselect(self):
       ##print 'drawselect'
        dc = wx.PaintDC(self)
        if dc.IsOk():
#            dc.SetFont(self.text.font)
            dc.SetBackgroundMode(wx.SOLID)
            dc.SetTextBackground('WHITE')
            dc.SetTextForeground('BLACK')
            dc.DrawLine(0, 0, 0, 10)
           ##print 'end'
            

    def leftdown(self, event):  
    
        self.text.Freeze()
        currentScroll = self.text.GetScrollPos(wx.VERTICAL)
        if self.upPoint > -1:
            self.text.SetStyle(self.downPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
#        #print 'line',self.text.GetScrollPos(wx.VERTICAL)/self.text.CharHeight,currentScroll/self.text.CharHeight
        while currentScroll < self.text.GetScrollPos(wx.VERTICAL):
            #print '<',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
            self.text.ScrollLines(-1)
              
        while currentScroll > self.text.GetScrollPos(wx.VERTICAL):
            #print '>',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
            self.text.ScrollLines(1)
            if currentScroll == self.text.GetScrollPos(wx.VERTICAL) + 1:
                break
        self.text.Thaw()
            
        self.text.Freeze()
        self.top_data.drag()
        event.Skip()
        return   
        self.trendFlag = True    
        currentScroll = self.text.GetScrollPos(wx.VERTICAL)
        
        self.text.Freeze()
        #print 'leftdown1,GetScrollPos,downPoint,upPoint',self.text.GetScrollPos(wx.VERTICAL),self.downPoint,self.upPoint
        (res, downPoint) = self.text.HitTestPos(event.GetPosition())
        if self.upPoint > -1:
            self.text.SetStyle(self.downPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
#        #print 'line',self.text.GetScrollPos(wx.VERTICAL)/self.text.CharHeight,currentScroll/self.text.CharHeight
        while currentScroll < self.text.GetScrollPos(wx.VERTICAL):
            #print '<',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
            self.text.ScrollLines(-1)
              
        while currentScroll > self.text.GetScrollPos(wx.VERTICAL):
            #print '>',currentScroll,self.text.GetScrollPos(wx.VERTICAL)
            self.text.ScrollLines(1)
#        if currentScroll != self.text.GetScrollPos(wx.VERTICAL):   
#            if platform.release()=='XP':
#                if self.text.GetInsertionPoint()==self.text.GetLastPosition():
#                    while currentScroll < self.text.GetScrollPos(wx.VERTICAL):
#                        self.text.ScrollLines(-1) 
#                        
#                    while currentScroll > self.text.GetScrollPos(wx.VERTICAL):
#                            self.text.ScrollLines(1)   
#                else:
#                    self.text.ScrollLines((currentScroll/self.text.CharHeight)-(self.text.GetScrollPos(wx.VERTICAL)/self.text.CharHeight))
#            else:
#                self.text.ScrollLines((currentScroll/self.text.CharHeight)-(self.text.GetScrollPos(wx.VERTICAL)/self.text.CharHeight))        
        self.text.Thaw()  
        #print 'leftdown2,GetScrollPos,downPoint,upPoint',self.text.GetScrollPos(wx.VERTICAL),self.downPoint,self.upPoint
        self.upPoint = -1 
        self.previousPoint = -1
        self.trend = 1
        self.previousPoint = downPoint
        self.downPoint = downPoint
        ###print 'lelfdown2',self.downPoint,self.upPoint,self.trend,self.trendFlag 
        self.trendFlag = False       
        return
        
    
    def leftup(self, event):
        event.Skip()
        self.top_data.drop() 
        return      
        (res, self.upPoint) = self.text.HitTestPos(event.GetPosition())
        ###print 'lelfup',self.downPoint,self.upPoint
        #self.text.SetStyle(self.downPoint,self.upPoint,(wx.TextAttr('BLACK','BLUE', self.fontb)))        
        return
        event.Skip()
        return
        ###print 'lelfup',self.text.GetStringSelection()
        event.Skip()    
       
    def mouse(self, event):
        #####print 'mouse'
        ######print 'current row.....', self.text.PositionToXY(self.text.GetInsertionPoint())
        #######print 'mouse'
        #self.text.SetInsertionPointEnd() 
        
        #x,y = self.text.PositionToXY(self.text.GetInsertionPoint())
        #=======================================================================
        # ######print 'mouse'
        # ######print str(y)+' - '+str(x)
        # ######print self.text.GetLineLength(y-1)
        # ######print self.text.GetLineText(y-1)
        # ######print self.text.GetLineLength(y)
        # ######print self.text.GetLineText(y)
        # ######print self.text.GetLineLength(y+1)
        # ######print self.text.GetLineText(y+1)
        #=======================================================================

        #self.text.Remove(self.text.GetInsertionPoint(), self.text.GetInsertionPoint() + (self.text.GetLineLength(y)-x))
        #self.text.Replace(self.text.PositionToXY(self.text.GetInsertionPoint()), self.text.PositionToXY(self.text.GetInsertionPoint()+10))
        #self.update_insert()
        if self.dynamis_name == 'TOP':
            return 'break'
        elif self.dynamis_name == "VI" and self.VIlevel == 3:
            return 'break'
        
        else:
            return
            event.Skip()       


    def onFocuss(self, event):
       ##print 'focus'
       pass
    
    def on_left(self, evt):
        position = evt.GetPosition()
        (res, hitpos) = self.text.HitTestPos(position)
        ######print res
        ######print hitpos
        (col, line) = self.text.PositionToXY(hitpos)
        the_line = self.text.GetLineText(line)
        ####print('on_left:%s' % the_line)

        
    def getCursorPosition(self):
        
        if self.size - 1 >= self.text.GetLastPosition():
            return self.text.GetInsertionPoint()
        else:
            return ((self.indexText / self.size) * self.size) + self.text.GetInsertionPoint()
    
    def updatePosition(self, length, removeLines):
        #print 'updatePosition'
        x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
        last = 0
        for i in range(removeLines):                
            last = last + self.text.GetLineLength(i) + 1                       
           
        self.text.Remove(0, last)   
        time.sleep(0.05)
        self.text.SetInsertionPoint(self.text.XYToPosition(x, y - removeLines))
        self.indexText = self.text.GetLastPosition()
        
             
    def onBack(self, event):
        ######print 'onback'
#        self.update_insert()
        
#        self.text.SetStyle(self.text.GetInsertionPoint(),self.text.GetInsertionPoint(), wx.TextAttr('BLACK',wx.NullColour, self.fontn))
        #wx.TextAttr

#        if self.insert_temp<self.indexText and self.dynamis_name!="VI" and self.dynamis_name!="TOP":
#            self.text.SetInsertionPointEnd()  
#        if self.dynamis_name == "VI" and self.VIlevel==3:
#            self.text.SetInsertionPoint(self.text.XYToPosition(self.xtemp,self.ytemp)) 
        keycode = event.GetKeyCode()
        ##print 'onback :' +str(keycode)
        ###print wx.GetKeyState(wx.WXK_NUMLOCK)
        if keycode == wx.WXK_NUMLOCK:
            if self.statusbar.GetStatusText(6) != '':
                self.statusbar.SetStatusText('', 6)
            else:
                self.statusbar.SetStatusText('NUM', 6)
            return

        if keycode == wx.WXK_CAPITAL:
            if self.statusbar.GetStatusText(5) != '':
                self.statusbar.SetStatusText('', 5)
            else:
                self.statusbar.SetStatusText('CAP', 5)
            return
        
        if keycode == wx.WXK_TAB:            
            self.channel.send(chr(keycode))
            return
        elif keycode == wx.WXK_F2:
            self.top_data.delay()
        elif keycode == wx.WXK_F1:
            try:
                
                #print 'f1'
                pos = self.text.GetScrollPos(wx.VERTICAL)
                print pos
                self.text.SetStyle(0, 10, (wx.TextAttr(wx.NullColour, 'BLUE', self.fontb)))
                
                while pos < self.text.GetScrollPos(wx.VERTICAL):
                    self.text.ScrollLines(-1)
                return
                #print self.text.GetClientRect()
                #print self.text.GetScrollPos(wx.VERTICAL)
                #print self.text.GetScrollPos(wx.VERTICAL)/self.text.CharHeight
                #print self.text.GetScrollThumb(wx.VERTICAL)
                self.text.ScrollLines(-1)
            except Exception, e:
               ##print e
                pass
            
        elif keycode == wx.WXK_BACK:
            self.OnDisBksp(event)
        elif self.connected == False:
                return 'break'
        elif keycode == wx.WXK_UP:
            self.OnDisUp(event)
        elif keycode == wx.WXK_DOWN:
            self.OnDisDown(event)
        elif keycode == wx.WXK_LEFT:
            self.OnDisLeft(event)
        elif keycode == wx.WXK_RIGHT:
            self.OnDisRight(event)
        elif keycode == wx.WXK_DELETE:
            self.OnDisDelete(event)
        elif keycode == wx.WXK_RETURN:
            if self.dynamis_name == 'COMMAND':
                self.channel.send(chr(keycode))
                return
            else:
                return
        elif event.ControlDown() == True and keycode == 82:
            self.channel.send(chr(18))
            return
        elif (event.ControlDown() == True and keycode == 90) or (event.ControlDown() == True and keycode == 68):

            if self.top_data != None:
                ######print "out down"
                self.channel.send(chr(keycode - 64))
                self.comments_temp = keycode
                return 'break'
            else:
                return
        elif (event.ControlDown() == True and keycode == 82) :
            ###print 'vao day'
            self.channel.send(chr(keycode - 64))
            self.comments_temp = keycode
            return 'break'
        elif (event.ControlDown() == True and keycode == 76) :
            self.channel.send(chr(keycode - 64))
            self.comments_temp = keycode
            return 'break'  
        elif (event.ControlDown() == True and (keycode == 69 or keycode == 65 or keycode == 86 or keycode == 67)) :
            self.channel.send(chr(keycode - 64))
            self.comments_temp = keycode
            return 'break'   
        elif keycode == 27:
            
            if self.top_data != None :
                self.channel.send(chr(27))
                self.comments_temp = keycode
                return 'break'
            else:
                return
        else:

            event.Skip()

    def key(self, event):
        try:

            keycode = event.GetKeyCode()
            
            ##print 'keyc',keycode

            if self.dynamis_name == 'COMMAND':
                if keycode == 97:
                    ##print self.channel.recv_ready(),self.channel.send_ready()
                    pass
                if keycode < 257:
                    self.channel.send(chr(keycode))
                return  

            else:
                return
                #event.Skip()
        except Exception, e:
            ##print 'loi do keycode >256'
            ##print e
            pass
        finally:
            pass 
    
    def OnSendMessage(self, event=None):        
        try:            
            _msg = self.comments    
            #####print "msg",_msg
            x, y = self.text.PositionToXY(self.indexText)
            endLine = self.text.GetRange(self.text.XYToPosition(0, y), self.indexText)
            if endLine != self.locate and endLine.startswith(self.locate) == True :                
                comment_prefix = endLine[self.locate.__len__():].strip()
                endLine = False
            else:
                endLine = True
            comment_prefix = _msg.strip().split(" ")[0]
            #####print list(_msg)
            #####print list(comment_prefix)
            ######print _msg+'  _msg'
            #####print "endLine",endLine              
            '''if _msg.strip()=="exit" or _msg.strip()=="quit" or _msg.strip()=="bye":
                self.onsaveIndex()      
                os._exit(99)'''
#            if comment_prefix == "vi" or comment_prefix == "vim":
#                
#                ######print 'testest'+_msg.strip()
#                self.channel.send(_msg.strip()+"\n")
#                self.VIlevel=2
#                self.top_data=VI(self,_msg.strip())
#                self.top_data.start()
#                self.dynamis_name='VI'
#                if endLine==False:
#                    _msg = comment_prefix + _msg
#                self.command_store.append(_msg.strip())
#            else:
#                self.channel.send(_msg.strip()+"\n")
#                self.VIlevel=2
#                self.top_data=COMMAND1(self,_msg.strip())
#                self.top_data.start()
#                self.dynamis_name='COMMAND'
#                if endLine==False:
#                    _msg = comment_prefix + _msg
#                self.command_store.append(_msg.strip())
            self.channel.send(_msg.strip() + "\n")
            self.VIlevel = 2
            self.top_data = COMMAND1(self, _msg.strip())
            self.top_data.start()
            self.dynamis_name = 'COMMAND'
            if endLine == False:
                _msg = comment_prefix + _msg
            self.command_store.append(_msg.strip())
            
            return
                
            
        finally:
            pass
            
     
    def OpenSendFileDlg(self):
        self.Enable(False)
        sendFileDlg = TranferFileDlg(self)
        sendFileDlg.callback = self.x.next
        sendFileDlg.CenterOnParent()
        sendFileDlg.Show()
        sendFileDlg.Raise()
        yield None
        self.Enable(True)
        yield None
    
    def OnSendFileNew(self, event):
        self.x = self.OpenSendFileDlg()
        self.x.next()
        
    def OpenSettingDlg(self):
        self.Enable(False)
        connectDlg = SettingDlg(self)
        connectDlg.callback = self.x.next
        connectDlg.CenterOnParent()
        connectDlg.Show()
        connectDlg.Raise()
        yield None
        self.Enable(True)
        yield None
    
    def OpenConnectDlg(self):
        self.Enable(False)
        connectDlg = ConnectDlg(self)
        connectDlg.callback = self.x.next
        connectDlg.CenterOnParent()
        connectDlg.Show()
        connectDlg.Raise()
        yield None
        self.Enable(True)
        yield None
    
    def openNotepad(self):
        if self.channel!="":
            self.Enable(False)
            notepadDlg = NotepadDlg(self)
            notepadDlg.callback = self.x.next
            notepadDlg.CenterOnParent()
            notepadDlg.Show(True)
            notepadDlg.Raise()
            notepadDlg.menuOpen(None)
            yield None
            self.Enable(True)
            yield None

    def OpenNewOrEditDlg(self):
        self.Enable(False)
        connectDlg = NewOrEditDlg(self)
        connectDlg.callback = self.x.next
        connectDlg.CenterOnParent()
        connectDlg.Show()
        connectDlg.Raise()
        yield None
        self.Enable(True)
        yield None
    
    def OnConnect(self, event):
        self.x = self.OpenConnectDlg()
        self.x.next()
    
    def OnNotePad(self, event):
        self.x =  self.openNotepad()
        self.x.next()
        
    def OnSetting(self, event):
        self.x = self.OpenSettingDlg()
        self.x.next()
        
    def OnReconnect(self):
        self.x = self.OpenConnectDlg()
        self.x.next()
        
    def OnDisconnect(self, event):
        self.Disconnect()
        
    def Disconnect(self):
        self.client.close()
        self.isconnect = False
        self.UpdateStatusControl()
        if self.top_data != None:
            try:
                self.top_data.__stop()
            except:
                pass        
        self.settingForBeginning()
        
        
    def OnNew(self, event):
        self.x = self.OpenNewOrEditDlg()
        self.x.next()
        
    def OnExit(self, event):
        self.Close()
                
    def OnClose(self, event):
        if self.namecn != "":
            write = WriteLogDB("logout", self.hostnamecn, self.usernamecn, self.pwcn, True)
            write.start()        
        event.Skip()
        
    def OnStop(self, event):
        try:
            self.client.close()
            self.channel = None
            self.top_data.__stop()
        except:
            pass
            
    def OnSendFile(self, event):
        self.sendfile = 1
        time.sleep(0.5)
        if not self.isconnect:
            wx.MessageBox("Required connect to server", "Notice", wx.OK)
            return
        elif re.search(r'\[[^\[]+\@[^\[]+ [^\[]+\].*', self.text.GetLineText(self.text.GetNumberOfLines() - 1), re.DOTALL) == None:
            wx.MessageBox("Stop your current process.", "Notice", wx.OK | wx.ICON_INFORMATION)
            return
        dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", "All files (*.*)|*.*", wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            self.filepath = []
            self.filepath.append(dialog.GetPath())
            ######print self.filepath 
        else:
            return
        dialog.Destroy()
        self.ProcessSendFile()
            
    def ProcessSendFile(self):     
        if(len(self.filepath) != 0):
            try:
                paramiko.util.log_to_file('log.txt')
                try:
                    self.text.AppendText('Starting transfer file.....')
                    self.text.Enable(False)
                    lastLine = self.text.GetLineText(self.text.GetNumberOfLines() - 1)
                    if re.search(r'--more--', lastLine) != None:
                        self.channel.send("q")
                    elif re.search(r'possibilities\? \(y or n\)', lastLine) != None:
                        self.channel.send("n")
                    else:    
                        self.channel.send(chr(27) + chr(26))
                    self.waiting = True
                    self.channel.send("\npwd\n")

                except Exception, e:
                    ##print e
                    self.waiting = False
                    self.text.Enable(True)
                    self.filepath = ''
                    pass
                self.indexText = self.text.GetLastPosition()
     
            except Exception, e:
                wx.MessageBox("Cannot send file to this server", "Error", wx.OK)
                self.indexText = self.text.GetLastPosition()
                self.waiting = False
                self.text.Enable(True)
                self.filepath = ''
                ######print type(e)
                ######print e
                return
            
    def uploadFile(self, pwd):
        self.text.AppendText('Waiting transfer file.....')
        fileError = ''
        try:
            sftp = self.channel.get_transport().open_sftp_client()
            sftp.chdir(pwd)
            filess = sftp.listdir(pwd)
            self.startSendFile = True
            self.indexFile = 0  
            self.numofFile = len(self.filepath)
      
            for files in self.filepath:
               ##print 'for'
                self.indexFile += 1
                basenames = os.path.basename(files)
                fileError = basenames
                self.file = files   
                if basenames in filess:
                    dlg = wx.MessageDialog(self, "Do you want to upload and replace file " + basenames + " ?", 'Notification', wx.YES_NO | wx.ICON_QUESTION)
                    if dlg.ShowModal() == wx.ID_YES:
                        dlg.Destroy()
                        sftp.put(files, basenames, callback=self.log_transfer)                
                        
                    else:
                        basenamen = ''
                        for num in range(100):
                            basenamen = basenames + '_' + str(num + 1)
                            if basenamen in filess:
                                pass
                            else:                            
                                break
                        sftp.put(files, basenamen, callback=self.log_transfer)                
                    
                else:
                    if not os.path.isdir(files):
                        sftp.put(files, basenames, callback=self.log_transfer)
                    else:
                        wx.MessageBox(basenames + ' not a file !', 'Error', wx.OK)
                                  
            self.filepath = ''
            x, y = self.text.PositionToXY(self.text.GetInsertionPoint()) 
            self.text.Remove(self.text.XYToPosition(0, y - 2), self.text.GetLastPosition())
            self.text.AppendText("Send file sucessfull.")                 
        except Exception, e:
           ##print 'loi 1',e
            self.waiting = False
            self.text.AppendText("\nCan't send file " + fileError + " to server !")
            self.filepath = ''
            pass
#        self.channel.send("mv ~"+ paths+'/' +basenamen +' '+ basenames + '\n')
        finally:
            self.text.Enable(True)
            self.channel.send('\n')
            
    def log_transfer(self, transferred, toBeTransferred):
        if self.startSendFile:
            self.startSendFile = False
           ##print toBeTransferred
            self.text.AppendText("\nTransferring: {0}/{1} files,\tStill to send: {2}Mb/{3}Mb ({4}%)\nSend file ".format(self.indexFile, self.numofFile, transferred / 1048576, toBeTransferred / 1048576, (transferred * 100) / toBeTransferred) + self.file + "\n")
        else:
            x, y = self.text.PositionToXY(self.text.GetInsertionPoint())
            self.text.Remove(self.text.XYToPosition(0, y - 2), self.text.GetLastPosition())
            self.text.AppendText("Transferring: {0}/{1} files,\tStill to send: {2}Mb/{3}Mb ({4}%)\nSend file ".format(self.indexFile, self.numofFile, transferred / 1048576, toBeTransferred / 1048576, (transferred * 100) / toBeTransferred) + self.file + "\n")
        
                
    def OnUpdate(self, event):
        self.Enable(False)
        updatedlg = UpdateApplication(self)
        updatedlg.start()
        ######print 'Update'
        
    def settingForBeginning(self):
        
        self.indexfind = 0
        self.link = None
        self.flagLink = True
        self.flagFindDialog = True
        self.runScript = False
        self.flagfocus = True
        self.startSendFile = True
        self.indexFile = 0
        self.numofFile = 0
        self.file = None
        #command VI
        self.down = 0
        self.up = 0
        self.pointsave = 0
        self.codeteamp = ''
        self.commanddd = False
        self.charpressd = False
        #self.firstrun = False
        self.xtemp = 0
        self.ytemp = 0
        self.VIlevel = 2
        self.frow = 0
        self.numflaginsert = 0
        self.flagonsize = True
        
        self.numend = 0
        self.numstart = 0
        
        #self.firstrun = True
        self.keypress = ''
        self.flaginsert = True
        #self.flagVI = True
        self.numstop = 1
        self.stoppoint = True
        self.rowdel = 0
        self.row = 0
        self.col = 0
        self.rowpaper = 0
        self.colpaper = 0
        self.flagcolor = False
        #statusbar
        self.statusbar.SetStatusText("", 1)
        self.statusbar.SetStatusText("", 2)
        self.statusbar.SetStatusText("", 3)
        self.statusbar.SetStatusText("", 4)
        self.statusbar.SetStatusText("", 5)
        self.statusbar.SetStatusText("", 6)
        #connection
        self.isresize = False
        self.term = 'vt100'
        self.size = 65536 
        self.listconnections = []
        self.namecn = ''
        self.hostnamecn = ''
        self.usernamecn = ''
        self.pwcn = ''
        self.port = 22
        self.currentItem = -1
        self.connected = False   
        self.co = 0       
        self.accept_host = ''
        self.filepath = ''
        ######print 'setttingForBeginning'
        # Param of SSH
        self.namecn = ""
        self.hostnamecn = ""
        self.usenamecn = ""
        self.pwcn = ""
        self.portcn = 22
        
        self.command = "ssh> "
        self.len_command = 0
        self.length_char = 0
        self.processing = False
        self.disable_text = ""
        self.char_last_text = ""
        self.msg_edit = ""
        self.msg = ""
        self.cmd = ""
        self.contents = ""
        self.contents2 = ""
        self.comments = ""
        self.comments_temp = ""
        self.previous_command = ""
        self.top_data = None
        self.sh_top_data = None
        #self.ipaddress = self.getPublicIp()
        self.current_folder = "."
        self.connect_folder = ""
        self.accept_login = ''
        self.locate = 'ssh> '
        self.path = 'abcd'
        self.sh_locate = ''
        self.flag_command = False
        self.returnCommand = False

        #Param of dynamis
        self.channel = None
        self.dynamis_name = None
        
        self.topIndex = 1.0
        self.endIndex = 1.0
        self.filename = ""
        self.waiting = False
        self.temp_store = []
        self.temp_lenght = -1
        self.tempArray = []
        self.vi_default = ['exit', 'qcr', 'q', 'Q', '!q', 'wq', 'x']
        self.lenght = 1
        self.press_key = False

        #Param of SFTP
        self.sftp_host = ''
        self.sftp_port = 22
        self.sftp_username = ''
        self.sftp_password = ''
        self.sftp_msg = ''
        self.sftp_process = False
        self.sftp_check_password = False
        self.sftp_check_login = False
        self.sftp_maintain = False
        self.stdin = None
        self.stdout = None
        self.sftp = None

        # Variable Configure
        #self.text.config(state=Tkinter.DISABLED)
        self.fileopen = self.getPathDocument() + r"\py_ssh.data"
        
        #self.current_work = ""
        self.numkeywait = 0
        self.editmode = False
        self.listBold = []
        self.command_store = []
        self.sh_command_store = []
        self.command_key = -1
        self.input_command_len = 0
        self.disleft = False
        #self.text.config(state=DISABLED)
        
       
    def UpdateStatusControl(self):
        if not self.isconnect:
            self.menuFile.FindItemById(2).Enable(False)
            self.menuFile.FindItemById(1).Enable(True)
            self.btnconnect.Enable(True)
            self.btndisconnect.Enable(False)
            self.btnsend.Enable(False)
            self.btnNotepad.Enable(False)
            self.text.Clear()
            self.text.Enable(False)
        else:
            self.menuFile.FindItemById(2).Enable(True)
            self.menuFile.FindItemById(1).Enable(False)
            self.btnconnect.Enable(False)
            self.btndisconnect.Enable(True)
            self.btnsend.Enable(True)
            self.btnNotepad.Enable(True)
            self.text.Clear()
            self.text.Enable(True)
            
        self.toolbar.Refresh()
        
    def getPublicIp(self):
        try:
            data = str(urllib.urlopen('http://checkip.dyndns.com/').read())
            return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(str(data)).group(1)
        except:
            return ""
    def setHiddenFile(self, pathfile):
        p = os.popen('attrib +h ' + pathfile)
        p.read()
        p.close()

    def setNormalFile(self, pathfile):
        try:
            win32api.SetFileAttributes(pathfile, win32con.FILE_ATTRIBUTE_NORMAL)
        except:
            pass    
    def getPathDocument(self):
        dll = ctypes.windll.shell32
        buf = ctypes.create_unicode_buffer(MAX_PATH + 1)
        if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):
            return buf.value
        else:
            return None
        
    def LoadDataConnection(self):
        if os.path.exists(self.fileopen):
            self.setNormalFile(self.fileopen)
            fopen = open(self.fileopen, 'r')
            data = fopen.read()
            fopen.close()
            self.setHiddenFile(self.fileopen)
            dataconnections = data.split('~!@#$%^&&*')
            self.listconnections = []
            
            for i in dataconnections:
                listconnections = []
                for j in i.split(";"):
                    listconnections.append(j)
                self.listconnections.append(listconnections)
                
        self.listconnections.sort(reverse=False);

                
    def WriteFileConnection(self, flag):
        
        # command New or Edit
        if flag:
            if os.path.exists(self.fileopen):
                self.setNormalFile(self.fileopen)
                fopen = open(self.fileopen, 'w')
                data = ""
                ######print range(len(self.listconnections))                 
                for i in range(len(self.listconnections)):
                    name, host, username, password = self.listconnections[i] 
                    if i == 0:
                        data = name + ";" + host + ";" + username + ";" + password
                    else:
                        data = data + '~!@#$%^&&*' + name + ";" + host + ";" + username + ";" + password
                fopen.write(data)
                fopen.close()
            else:
                fopen = open(self.fileopen, 'w')
                name, host, username, password = self.listconnections[0]
                fopen.write(name + ";" + host + ";" + username + ";" + password)
                fopen.close()
        
    
    def ChangeMenuBarColor(self):
        """
        Changes the background color of the menubar and optionally gives 
        different colors to menu items
        """
        user32 = windll.user32
        DrawMenuBar = user32.DrawMenuBar
        GetMenu = user32.GetMenu
        GetSubMenu = user32.GetSubMenu
        #GetSystemMenu = user32.GetSystemMenu
        SetMenuInfo = user32.SetMenuInfo
        #GetMenuInfo = user32.GetMenuInfo
        gdi32 = windll.gdi32
        CreateSolidBrush = gdi32.CreateSolidBrush
        # Instantiate MENUINFO
        menuinfo = MENUINFO()
        # Important to set the size
        menuinfo.cbSize = sizeof(MENUINFO)
        menuinfo.fMask = win32con.MIM_BACKGROUND
        if not self.bShadeSubMenus:
            menuinfo.fMask |= win32con.MIM_APPLYTOSUBMENUS
        menuinfo.hbrBack = CreateSolidBrush(COLORREF(255, 255, 255))
        # Important! Pass *pointer* of the menuinfo instance to the win32 call
        SetMenuInfo(GetMenu(self.hwnd), pointer(menuinfo))
        if self.bShadeSubMenus:
            menuinfo.fMask = win32con.MIM_BACKGROUND | win32con.MIM_APPLYTOSUBMENUS
            menuinfo.hbrBack = CreateSolidBrush(COLORREF(255, 255, 0))
            SetMenuInfo(GetSubMenu(GetMenu(self.hwnd), 0), pointer(menuinfo))
            menuinfo.fMask = win32con.MIM_BACKGROUND | win32con.MIM_APPLYTOSUBMENUS
            menuinfo.hbrBack = CreateSolidBrush(COLORREF(128, 255, 128))
            SetMenuInfo(GetSubMenu(GetMenu(self.hwnd), 1), pointer(menuinfo))
        DrawMenuBar(self.hwnd)

def SettingWinSecurity(handle):
    dlluser32 = ctypes.WinDLL('user32.dll')      
    MSGFLT_ALLOW = 1
    MSGFLT_ADD = 1
    dlluser32.ChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD);
    dlluser32.ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD);
    dlluser32.ChangeWindowMessageFilter(0x0049, MSGFLT_ADD);
#    dlluser32.ChangeWindowMessageFilterEx(handle,WM_DROPFILES, MSGFLT_ALLOW,None)
#    dlluser32.ChangeWindowMessageFilterEx(handle,WM_COPYDATA, MSGFLT_ALLOW,None)
#    dlluser32.ChangeWindowMessageFilterEx(handle,0x0049, MSGFLT_ALLOW,None)
    #wx.MessageBox(str(a) + ' ' + str(b) + ' ' + str(c),'Notice',wx.OK)
 
def _to_unicode(s):
       """
       decode a string as ascii or utf8 if possible (as required by the sftp
       protocol).  if neither works, just return a byte string because the server
       probably doesn't know the filename's encoding.
       """
       try:
           return s.encode('ascii')
       except UnicodeError:
           try:
               return s.decode('utf-8')
           except UnicodeError:
               return s         

if __name__ == '__main__':
    try:
        bShadeSubMenus = sys.argv[1]
    except:
        bShadeSubMenus = False
    
    app = wx.PySimpleApp()
    root = SSH(shadesubmenus=bShadeSubMenus)
    root.Show()
    app.MainLoop()
